根据道具状态有条件地重定向用户

时间:2019-08-31 20:33:15

标签: reactjs redux react-router

我有一个Dashboard组件,我试图根据用户是否已创建帐户来有条件地重定向用户。如果他们当前没有帐户,则需要将其重定向到我的CreateAccount组件。如果他们已经有一个帐户,我想将它们重定向到我的SelectAccount组件。

使用以下代码,我已经有帐户的用户不断重定向到我的“创建帐户”组件。我感觉这段代码返回了true,因为它在填充道具之前就运行检查,但是不确定如何解决。

class Dashboard extends React.Component {
    componentDidUpdate(prevProps) {
      if (prevProps.accounts !== this.props.accounts && (!this.props.activeAccount && this.props.accounts)) {
        if (!_.isEmpty(this.props.accounts)) {
          history.push('/accounts/selectAccount');
        }
      }

      if (prevProps.accounts !== this.props.accounts && (_.isEmpty(this.props.accounts) === true)) {
        if (_.isEmpty(this.props.accounts)) {
          history.push('/accounts/createAccount');
        }
      }
    }

编辑:要解决此问题,我添加了以下代码:

  componentDidUpdate(prevProps, prevState) {
    if (this.props.accounts !== prevProps.accounts && _.size(this.props.accounts) >= 1) {
      console.log("I see some accounts")
    }
    if (this.props.accounts !== prevProps.accounts && _.isEmpty(this.props.accounts)) {
      console.log("There are no accounts")
    }

发生的事情是,对于已经拥有帐户的用户,在渲染的第一个迭代中,它说“没有帐户”,然后是“我看到一些帐户”。在我的api调用之后,有什么方法可以使这种逻辑起作用?

0 个答案:

没有答案