首页 > 解决方案 > 条件渲染然后清除状态(警告/错误)

问题描述

在我的componentDidMount中,我正在获取数据,然后setState用于存储该数据。在我的render中,我根据我的状态有条件地渲染/重定向到一个组件,但是我需要清除我的状态,以免它陷入无限的重定向循环。但是,当我在我的 中调用该函数进行重定向时render,我收到了一个警告Cannot update during an existing state transition (such as within render)。我应该如何解决这个问题?

componentDidMount() {
  let branchKeyTest = 'key_test_b'  
  branch.init(branchKeyTest, (err, data) => {
    this.setState({ redirectPath: data })
  }
  this.setState({ isLoading: false })
}) 


redirectToPath = (path) => {
    const { history } = this.props;
    history.push(path);
    this.setState({ redirectPath: null })   
  }

render() {
    const { isLoading, redirectPath } = this.state;
    const { token, location } = this.props;
    const loggedIn = !!token;


    if (!isLoading && loggedIn && (redirectPath != null)) {
      switch (redirectPath.link_type) {
        case 'new_release':
            this.redirectToPath(`/releases/releaseinfo/${redirectPath.id}`)
          break;
        default:
          return;
      }
    }

    if (!isLoading) {
      return (
        <div>Done Loading</div>
      );

    }
    else {
      return (<h1>Loading...</h1>)
    }
 }

标签: reactjs

解决方案


推荐阅读