0

这是我的组件中的代码:

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 调用时,组件会无限渲染,我不知道如何处理,我只想要一个简单的重定向到另一条路线。谢谢!

4

2 回答 2

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;
      }
    }
于 2018-10-23T11:30:45.330 回答
0

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

尝试更改路线的顺序

<Switch>
    <Route path={`${match.url}/dashboard`} component={Dashboard} />
    <Route exact path={`${match.url}/`} component={MyComp} />
</Switch>
于 2018-10-23T10:50:08.070 回答