因此,我在AppRouter.js中管理用户身份验证,这是我的最高组件。

下面是它的工作原理:

componentDidMount() {
  this.getUser()
}

getUser(history = undefined) {
  const { cookies } = this.props
  let jwt = cookies.get(this.state.cookieName)
  if (!jwt) return null

  AuthApi.getCurrentUser(jwt).then(response => {
    if (response !== undefined) {
      this.setState({
        email: response.email,
        userId: response.id,
        firstName: response.first_name,
        lastName: response.last_name,
        phoneNumber: response.phone_number,
        randomString: response.random_string,
        jwt: jwt
      })
      if (history) history.push('/')
    }
    else {
      // user has cookie but cannot load current user
      cookies.remove(this.state.cookieName)
      this.setState({
        email: undefined,
        firstName: undefined,
        lastName: undefined,
        phoneNumber: undefined,
        randomString: undefined,
        jwt: undefined,
        userId: undefined
      })
    }
  })
}


我的问题是,我还在子组件中调用了componentDidMount(),那里的代码取决于我的AppRoutercomponentDidMount()输出结果。

这是我的MyOrdersPage.js组件接收AppRouter状态作为道具的示例:

componentDidMount() {
    axios.get('/api/v1/orders/' + this.props.currentUser.userId)
    .then(response => {
      console.log(response)
        this.setState({
            orders: response.data
        })
    })
    .catch(error => console.log(error))
  }


但是,AppRoutercomponentDidMount()MyOrdersPage.jscomponentDidMount()之后完成加载。因此,当this.props.currentUser.userIdundefined运行时,MyOrdersPage.jscomponentDidMount()

如何更改代码,以使子组件中的componentDidMount()仅在componentDidMount()中的AppRouter.js加载完成后才加载?

最佳答案

正如@skyboyer在评论中提到的,我向父组件添加了状态isReady,默认情况下设置为false。 API调用加载完成后,它将变为true

AuthApi.getCurrentUser(jwt).then(response => {
    if (response !== undefined) {
      // do something
    }
    else {
      // do someting else
    }
  }).then(() => this.setState({isReady: true}));


并在render()方法中:

{this.state.isReady &&
        <div>...</div>}


此外,实现react-loads也是一个好主意。

10-05 20:41
查看更多