【问题标题】:Redirect to nested route with react-router v4使用 react-router v4 重定向到嵌套路由
【发布时间】:2018-02-21 03:41:23
【问题描述】:

当我尝试重定向到嵌套的 url 时,它似乎进入了无限循环。

<Router history={browserHistory}>
  <Route path="/nse" component={App} />
</Router>

在 App 组件中,

if(visibleContainerProp == 4){          
  return <Redirect to={`${match.url}/stockdetails/${searchticker}`} />
}

这里,visibleContainerProp 是从文档中提到的状态读取的 https://reacttraining.com/react-router/web/example/auth-workflow

每次用户从搜索框中选择一个代码并尝试重定向到上述网址时,我都会将 visibleContainerProp 设置为 4。但它失败了。

在浏览器中我看到 url http://127.0.0.1:8000/nse/stockdetails/BBTC,在控制台中我看到它尝试加载几次并以警告结束

Warning: You tried to redirect to the same route you're currently on: "/nse/stockdetails/BBTC"

但是,如果我直接通过应用程序组件不重定向到 url,它就可以完美运行。在 App 组件中,我有以下内容。

<Switch>
  <Route path={`${match.url}/index`} component={AIContainer}/>
  <Route path={`${match.url}/equity`} component={EQContainer}/>
  <Route path={`${match.url}/quickstats`} component={StatsContainer}/>
  <Route path={`${match.url}/stockdetails/:ticker`} component={StockSearchDetails}/>
  <Route component={ScreenContainer}/>
</Switch>

我知道文档中的示例不使用重定向到嵌套路由。这可能吗?

谢谢

【问题讨论】:

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


    【解决方案1】:

    是的,它的无限循环,因为您没有将visibleContainerProp 重置为其他值。它坚持使用4

    代替

    if(visibleContainerProp == 4){          
      return <Redirect to={`${match.url}/stockdetails/${searchticker}`} />
    }
    

    首先发送一个动作,该动作将重置visibleContainerProp

    if(visibleContainerProp == 4){          
           dispatch({ type : 'UPDATE_MY_PARAM_TO_RESET_REDIRECTION'})
          return <Redirect to={`${match.url}/stockdetails/${searchticker}`} />
    }
    

    在App组件中,通过mapStateToProps读取visibleContainerProp,这将有助于您管理 visibleContainerProp==4 条件并避免循环重定向。

    编辑:

    通过检查条件if(visibleContainerProp == 4),根据您的要求从适当的组件生命周期中调用操作redirectAction

    redirectAction(redirectUrl){
    
              /this will update `visibleContainerProp` to some other value
             dispatch({ type : 'UPDATE_MY_PARAM_TO_RESET_REDIRECTION'});
             //create history object and push the next url
             history.push(`${match.url}/stockdetails/${searchticker}`);
    }
    

    【讨论】:

    • 感谢 Riyaj 不允许在渲染中更改状态,我收到警告:setState(...): Cannot update during an existing state transition(例如在render 或其他组件的构造函数中)。渲染方法应该是 props 和 state 的纯函数;构造函数副作用是一种反模式,但可以移至componentWillMount
    • 是的。这就是它在文档中的完成方式。所以我按照例子
    • 重定向后要渲染哪个组件?
    • 我想渲染 StockSearchDetails 组件。与 switch 语句中的相同。所以 ${match.url}/stockdetails/:ticker} 组件={StockSearchDetails}/>。我应该说上面的技巧确实有效,但我想知道是否有一个符合模式的解决方案。
    • 我想即使添加了更多标签,也没有进一步的答案。所以我会接受你的回答,因为它有效。可能我问了一个错误的问题,或者可能是错误的方式。不过,你解决了我的直接问题。所以非常感谢。干杯。
    猜你喜欢
    • 2017-08-28
    • 2019-01-07
    • 2017-06-25
    • 2017-11-11
    • 2018-06-06
    • 1970-01-01
    相关资源
    最近更新 更多