更改道具历史会导致重定向循环React

时间:2018-10-23 10:04:04

标签: javascript reactjs react-router react-router-v4

这是我在组件中的代码:

class MyComp extends React.Component {

  componentDidMount(){
    this._isMounted = true;
    axios.get(URL).
    then(res => {
      if(this._isMounted) {
        if(res=="ok")
          this.props.history.push("en/dashboard");
        }
    })
  }

  componentWillUnmount(){
    this._isMounted = false;
  }
}

我的带路线的index.js:

<Switch>
  <Route exact path={`${match.url}/`} component={MyComp} />
  <Route path={`${match.url}/dashboard`} component={Dashboard} />
</Switch>

当我执行axios调用时,组件无限渲染,但我不知道如何处理,我只想简单地重定向到另一条路线。谢谢!

2 个答案:

答案 0 :(得分:0)

从MyComp重定向后,似乎总是match.url en/dashboard

尝试更改路线的顺序

<Switch>
    <Route path={`${match.url}/dashboard`} component={Dashboard} />
    <Route exact path={`${match.url}/`} component={MyComp} />
</Switch>

答案 1 :(得分:0)

您可以怀抱希望,这对您有帮助。

<Switch>
    <Route exact path={`/:language/dashboard`} component={Dashboard} />
    <Route exact path={`/:language`} component={MyComp} />
</Switch>

 class MyComp extends React.Component {

      componentDidMount(){
        this._isMounted = true;
        axios.get(URL).
        then(res => {
          if(this._isMounted) {
            if(res=="ok")
              this.props.history.push("/en/dashboard");
            }
        })
      }

      componentWillUnmount(){
        this._isMounted = false;
      }
    }