【发布时间】:2023-03-21 09:20:02
【问题描述】:
经过几个小时的谷歌搜索,我使用可用路由参数改变 location.state 的解决方案都失败了,所以请转至这里使用这个用例:
我被限制使用:
"react-router": "^3.2.4", "react-router-dom": "^5.1.2"
路由“/a/b/”上的组件有 location.state.somevar,我需要改变这个“somevar”,以防路由有诸如“/a/b/:c”之类的参数,这样一些变量=c
我的解决方案是有 2 个路由,一个将从 props 读取参数,如果 /:c 可用,则路由将包含:
<Redirect to={pathname: '/a/b', state: {somevar: 'c'}/>
但在这种情况下我得到错误:
<Redirect> elements are for router configuration only and should not be rendered
所有使用 withRouter 等的尝试都失败了。
请提出解决方案。
编辑:
这只是希望它对类似情况的人有所帮助:
我尝试将重定向组件与路由器 v3 一起使用的任何方式都失败了!
最终,我在 Route 组件内部制作了一个组件,例如:
<Route path="/somewhere" component={()=>{ // detail }
并返回一个微调器,同时等待来自 api 调用的数据,通过 useContext 像:
const expectedData = useContext(SomeContext)
并有条件地返回我说的那个微调器,或者如果 expectedData 可用的话:
// inside component:
const { router } = props
if(expectedData){
router.push({pathname: '/newPath/', state: {some:'thing'})
return null //important! you must return something as a React function
}
return <Spinner />
就是这样。希望这对某人有所帮助。
【问题讨论】:
标签: reactjs react-router react-router-dom