【问题标题】:ReactJS - Pass props with Redirect componentReactJS - 使用重定向组件传递道具
【发布时间】:2019-02-03 11:12:33
【问题描述】:

你应该如何通过 Redirect 组件传递道具而不让它们暴露在 url 中?

喜欢这个<Redirect to="/order?id=123 />"?我正在使用react-router-dom

【问题讨论】:

    标签: javascript reactjs react-router-dom


    【解决方案1】:

    您可以像这样使用浏览器历史状态:

    <Redirect to={{
        pathname: '/order',
        state: { id: '123' }
    }} />
    

    然后你可以通过this.props.location.state.id访问它

    来源:https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/Redirect.md#to-object

    【讨论】:

    • this.props.location 给我未定义。有什么建议吗?
    • @DhruvSinghal 这意味着您的组件无权访问路由器道具。也许尝试用withRouter 包装你的组件
    • @SagarKodte 同样,我是第一个 :)
    • 我收到此错误Expected an assignment or function call and instead saw an expression。有什么建议吗?
    【解决方案2】:

    您可以像这样使用Redirect 传递数据:

    <Redirect to={{
                pathname: '/order',
                state: { id: '123' }
            }}
    />
    

    您可以通过以下方式访问它:

    this.props.location.state.id
    

    API docs 解释了如何在 Redirect / History 属性中传递状态和其他变量。

    来源:https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/Redirect.md#to-object

    【讨论】:

    • @SakhiMansoor 是的,该对象应包含 pathnamesearchstate 等,它们是浏览器历史记录使用的值。任何自定义值都应包含在下一层的state 对象中。它更干净,并将浏览器历史记录使用的内容与您自己的自定义对象分开。
    • 感谢@Anas 和 SakhiMansoor 的帮助。你们俩都应该得到解决方案标记! :)
    • @SakhiMansoor 我尝试了相同的代码,但它给了我这个错误:对象文字可能只指定已知属性,并且 'id' 在类型 'LocationDescriptor' 中不存在。
    • 这显然有效 ;
    • 嗨...我在接收通过重定向传递的状态参数时遇到了一些问题。 this.props.location 给了我未定义的。有什么建议吗?
    【解决方案3】:
    • 您可以使用自己的挂钩来达到同样的目的:
    import { createBrowserHistory } from "history";
    
    const withRefresh = createBrowserHistory({ forceRefresh: true });
    const ROOT_PATH = process.env.PUBLIC_URL || "/myapp";
    
    const useRedirectToLocation = (params="1") => {
    if(params){
    withRefresh.push({
        pathname: `${ROOT_PATH}/create`,
        state: { id: `${params}` }
      });
    }
    } 
    
    export default  useRedirectToLocation;
    
    
    • 并像这样使用它:
    
     import useRedirectToLocation from  './useRedirectToLocation
    
    
    const handleOnClick = params => useRedirectToAccounting(params)
    
    const RedirectorComponent = () => <a onClick={handleOnClick}>{"Label"}</a>
    

    ** 这可以根据需求进一步重构。

    【讨论】:

      【解决方案4】:

      您应该首先在您在 App.js 中定义的 Route 中传递道具

      <Route path="/test/new" render={(props) => <NewTestComp {...props}/>}/>
      

      然后在你的第一个组件中

      <Redirect
                  to={{
                  pathname: "/test/new",
                  state: { property_id: property_id }
                }}
              />
      

      然后在您的重定向 NewTestComp 中,您可以像这样在任何您想要的地方使用它

      componentDidMount(props){
      console.log("property_id",this.props.location.state.property_id);}
      

      【讨论】:

      • 被低估的答案-这是一个完整的解决方案;简单地在上述答案中添加这一行并不能正确传递道具。
      • 这是关键部分。至少可以说简单且非常有帮助!
      • 标记为新的正确答案,因为这个答案有更多信息。
      • 您能否详细说明“然后在您的第一个组件中”?我很难将这一切组合在一起。哪个组件是“第一个组件”?
      • @sammms 不是作者,但我相信他们只是在重定向组件中。您可以将其添加到您希望传递道具的任何重定向组件中,前提是 Route 组件具有作为函数设置的渲染道具。 See here for more about Redirect tohere for more about Route render
      【解决方案5】:
      <Redirect to={{
          pathname: '/path',
          state: { id: '123' }
      }} />
      

      然后你可以通过所需组件中的this.props.location.state.id访问它

      【讨论】:

        【解决方案6】:

        使用功能组件/钩子,react-router-dom 版本 5.2.0 并传递函数和常规道具:

        使用@Barat Kumar 回答,在这里您还可以看到如何使用 Redirect 将函数作为道具传递和访问。请注意,您访问 property_id 属性的方式也有所不同。

        路线是一样的:

        <Route path="/test/new" render={(props) => <NewTestComp {...props}/>}/>
        

        重定向:

        <Redirect
          to={{
            pathname: "/test/new",
            testFunc: testFunc,
            state: { property_id: property_id }
          }}
        />
        

        在 NewTestComp 中访问两个道具:

         useEffect(() => {
           console.log(props.history.location.testFunc);
           console.log(props.history.location.state.property_id);          
         }, []);
        

        请注意,“状态”来自于类组件中的使用。在这里,您可以使用任何您想要的名称,也可以像我们执行该函数一样传递常规道具。因此,与@Barat Kumar 接受的答案稍有不同,您可以:

        <Redirect
          to={{
            pathname: "/test/new",
            testFunc: testFunc,
            propetries: { property_id: property_id1, property_id2: property_id2},
            another_prop: "another_prop"
          }}
        />
        

        然后像这样访问:

        console.log(props.history.location.testFunc);
        console.log(props.history.location.propetries.property_id1);
        console.log(props.history.location.propetries.property_id2);
        console.log(props.history.location.another_prop);
        

        【讨论】:

          猜你喜欢
          • 2019-05-04
          • 2019-08-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-11-19
          • 2017-11-24
          • 2021-09-03
          相关资源
          最近更新 更多