等待componentDidMount中的redux道具

时间:2018-08-27 10:40:24

标签: reactjs redux jwt

我想从componentDidMount的API端点中加载某些内容,但这需要将redux存储中的其他内容传递到其中。

事实是,似乎在从Redux填充道具之前会触发componentDidMount,因此jwt auth令牌尚未处于redux状态,并且我收到401错误。

如何获取代码以等待redux状态被加载,然后调用该函数,或者让它每循环一次(比如说500毫秒),直到识别出道具为止?

如果除了componentDidMount以外还有其他地方,我应该提出建议。

2 个答案:

答案 0 :(得分:3)

您使用componentWillReceiveProps生命周期方法来跟踪传入的道具。

componentWillReceiveProps(nextProps){
 if(this.props.auth.token !== nextProps.auth.token){
   //make a api call here
 }
}

答案 1 :(得分:1)

您可以等待auth令牌获得价值。 例如,您可以显示进度指示器,直到获得值为止。如果它收到一个值,则显示带有componentDidMount的组件。

render() {
   const {authToken} = this.props;
   return (
     <div> 
       {!authToken && ProgressIndicator}
       {authToken && ComponentWithApiFetch}
     </div> 
   )
}
相关问题