【问题标题】:react-router v3.2.4 redirect issuereact-router v3.2.4 重定向问题
【发布时间】: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


    【解决方案1】:

    我认为您的问题是您没有将正确的对象传递给&lt;Redirect /&gt;

    <Redirect to={pathname: '/a/b', state: {somevar: 'c'}/>
    

    应该是:

    <Redirect to={{ pathname: '/a/b', state: {somevar: 'c'} }}/>
    
    // which is
    <Redirect to={{
      pathname: '/a/b', 
      state: { somevar: 'c' }
    }}/>
    

    我拆开它是为了让您可以看到该对象,您需要在{} 中添加{} 以表明它是一个对象。

    【讨论】:

    • 谢谢,这不是问题所在,因为在我的问题文本中我有错别字,但在代码中我正确地写了一个正确的对象(我从文档中复制/粘贴)。问题依然存在。
    • @Newjavascripter 不用担心,我绝对建议您在问题中使用尽可能接近正确的代码,因为很多时候这些问题都是简单的拼写错误,我们可以帮助您发现它们。如果那不是代码,那就更难了
    • 很抱歉我无法投票给你,因为我还没有足够的声誉:-)
    【解决方案2】:

    在我的解决方案中,您应该使用单一路由来处理此问题。

    您的路线:

    <Route path="/a/b/:someVar" component={YourComponent}>
    

    你的组件:

    const { someVar } = this.props.match.params
    // is will replace your url without reload or redirect
    this.props.history.replace({pathname: '/a/b'})
    

    【讨论】:

    • 谢谢,但这不会改变 props.location.state.someVar,这是我的要求 :(
    • 我没有投票给你只是因为没有足够的票让我这样做。对不起! :-)
    猜你喜欢
    • 2019-06-28
    • 1970-01-01
    • 1970-01-01
    • 2021-11-12
    • 1970-01-01
    • 2018-07-15
    • 1970-01-01
    • 2022-06-24
    • 2016-01-22
    相关资源
    最近更新 更多