【问题标题】:HOC Redux Dispatch gets called after child component calls React componentDidMountHOC Redux Dispatch 在子组件调用 React componentDidMount 后被调用
【发布时间】:2018-09-08 22:55:15
【问题描述】:

我有一个高阶组件 (HOC),用于授权和刷新用户会话。

这是 RequireAuth HOC,它是 componentWillMount

componentWillMount() {
  console.log('HOC componentWillMount');
   // checks with authorizer that token is valid if not refresh token
    getUserFromLocalStorage()
      // update redux with new refresh token
      .then(data => {
        console.log('getUserFromLocalStorage')
        this.props.setUserToReduxState(data);
        console.log(
          'user sucess retrieved and user setUserToReduxState: ',
          data
        );
      })
      .catch(() => {
        logoutUserFromReduxState();
      });
  }
}

这是我的路线调用

<Route exact path="/devices" component={RequireAuth(Devices)} />

这是我的设备组件的 componentDidMount

componentDidMount() {
  console.log('componentDidMount')
  // calls api
  this.loadData();
}

此子组件调用需要令牌的 API。 但是,当令牌 get 刷新时,它会在设备组件中调用 API get 之前刷新,但是从 HOC 中的 '.then' 承诺返回的 redux 操作不会在子组件中的 api 调用之前更新 redux 状态.

有没有办法在孩子尝试调用 API 之前确保令牌已经更新/redux 状态?

【问题讨论】:

  • 在获取令牌时显示加载微调器或其他内容,而不是立即安装子组件

标签: javascript reactjs redux state amazon-cognito


【解决方案1】:

我认为你可以在你的 HOC 中添加一个条件来不呈现你的“增强组件”——在你的情况下是设备,直到 setUserToReduxState 被用户的令牌解决。只有在设置了用户的令牌后,您的设备组件才会呈现 loadDate 方法。

例如- 您可以将用户的状态映射到变量。如果用户不存在 - 不要渲染您传递给 HOC 的组件。

编辑:(添加代码 sn-p)

// In your render method get the current user from redux - see  mapStateToProps functoion
render(){
    const { user } = this.props;
    return (
        return (
        <div>
            {
              user && user.token
              ? <Component {...this.props} />
              : null // Here you can replace this with spinner if you want..
            }
        </div>
      )
    )
}


const mapStateToProps = (state) => ({
    user: state.auth.user
})

现在,当设置用户时,您的组件将重新渲染,并且设备组件将在确定设置令牌时触发 loadData 方法。

【讨论】:

  • 这是一个很好的答案。您可以通过包含一些基于 OP 代码的示例代码来使其成为一个很好的答案
  • @tsahnar 谢谢你。你能证明一个例子吗?谢谢
  • 我明白了,这很有意义。一旦通过身份验证,他们就会拥有一个每小时刷新一次并且代码会更改的令牌。有没有办法确保新的刷新令牌用于 API 调用?如果令牌刷新,redux 不会在子组件中触发 componentDidMount 之前更新状态。干杯@tsahnar
猜你喜欢
  • 2021-11-11
  • 2018-09-22
  • 2015-12-25
  • 2019-03-29
  • 1970-01-01
  • 2019-02-20
  • 2018-12-17
  • 2019-06-30
  • 1970-01-01
相关资源
最近更新 更多