使用 react-router v4 重定向到嵌套路由

Redirect to nested route with react-router v4

当我尝试重定向到嵌套 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。但它失败了。

在浏览器中我看到 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>

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

谢谢

是的,它是无限循环,因为您没有将 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}`} />
}

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

编辑:

调度一个动作redirectAction。根据您的要求通过检查条件if(visibleContainerProp == 4)

从适当的组件生命周期中调用它
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}`);
}