0

我有一个 api,它将列出当前用户拥有的所有访问权限,所以一旦 app.js 加载,我就会在 componentWillMount 中调用 api,所以基本上我有三个路由,家庭、用户列表、每个用户。所以主页是一个静态文本页面。

userslist 是我列出所有用户的组件,一旦您单击用户的编辑图标,它将带您进入每个用户组件中的用户详细信息。

问题在于,一旦 useraccessApi 解析并通过传递 useraccessApi 响应仅获取我应该调用 usersListApi 的数据,调用就是异步的。

我所说的快乐流程是第一个用户加载 localhost:3000/home 以便 useraccessApi 将调用并且 redux 有数据,因此在切换到 componenWillMount 上的 userslist 选项卡时它会起作用。但是如果用户直接选择 localhost:3000/userlist 它会在 componenWillMount 上抛出错误,因此将代码移动到 componentWillRecieveProps()。

那么我该如何解决这个问题。或者我应该使用 mergeProps 来解决它。

App.js


componenWillMount(){
 this.props.userAccessApi()
}


UsersList

componentWillMount(){
  const {currentUserAccess} = this.props
 // if its a happy flow else it will be currentUserAccess is undefined
 if(currentUserAccess){
   this.props.usersListApi(currentUserAccess)
 } 
}


// inorder to resolve it 

componentWillRecieveProps(nextProps){
  const {currentUserAccess} = nextProps
   if(currentUserAccess){
   this.props.usersListApi(currentUserAccess)
   } 
}


const mapStateToProps = (state) => {
  return {
    currentUserAccess: state.access
  } 
}

4

1 回答 1

0

这是 React 生命周期事件的预期行为。

ForcomponentWillMount 这个函数在组件第一次渲染之前被调用,所以乍一看它似乎是一个放置数据获取逻辑的完美位置。

但是,有一个“陷阱”:在渲染发生之前,获取数据的异步调用不会返回。这意味着组件将至少使用空数据呈现一次。这就是为什么您的调度功能失败并且您未定义的原因。

相反,您应该将ComponentDidMount其用作获取数据的事件。

componentDidMount调用的时候,组件已经被渲染了一次。

在实践中,componentDidMount是调用获取数据的最佳位置。

使用它可以清楚地表明在初始渲染之前不会加载数据。这会提醒您正确设置初始状态,这样您就不会出现导致错误的未定义状态。

于 2019-01-07T07:23:49.407 回答