ReactJS - 使用Redirect组件传递道具

Mic*_*iel 24 javascript reactjs react-router-dom

你应该如何使用Redirect组件传递道具而不将它们暴露在网址中?

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

Sak*_*oor 56

您可以使用以下方式传递数据Redirect:

<Redirect to={{
            pathname: '/order',
            state: { id: '123' }
        }}
/>
Run Code Online (Sandbox Code Playgroud)

这就是你如何访问它:

this.props.location.state.id
Run Code Online (Sandbox Code Playgroud)

用于在Redirect/History prop中传递状态和其他变量的API dcoumentation.

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

  • 感谢@Anas和SakhiMansoor的帮助.你们俩都应该得到解决方案!:) (2认同)
  • 嗨...我在接收通过重定向传递的状态参数时遇到了一些麻烦。this.props.location 给我未定义。有什么建议? (2认同)

小智 45

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

<Route path="/test/new" render={(props) => <NewTestComp {...props}/>}/>
Run Code Online (Sandbox Code Playgroud)

然后在你的第一个组件中

<Redirect
            to={{
            pathname: "/test/new",
            state: { property_id: property_id }
          }}
        />
Run Code Online (Sandbox Code Playgroud)

然后在您的 Redirected NewTestComp 中,您可以像这样在任何地方使用它

componentDidMount(props){
console.log("property_id",this.props.location.state.property_id);}
Run Code Online (Sandbox Code Playgroud)

  • 被低估的答案-这是一个完整的解决方案;仅在上述答案中添加该行并不能正确传递道具。 (3认同)

Ana*_*nas 12

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

<Redirect to={{
    pathname: '/order',
    state: { id: '123' }
}} />
Run Code Online (Sandbox Code Playgroud)

然后你可以通过它访问它 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给我未定义。有什么建议么? (2认同)

dan*_*ive 5

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

使用 @Barat Kumar 答案,在这里您还可以看到如何使用 Redirect 将函数作为 props 传递和访问。请注意,访问 property_id 属性的方式也存在差异。

路线是一样的:

<Route path="/test/new" render={(props) => <NewTestComp {...props}/>}/>
Run Code Online (Sandbox Code Playgroud)

重定向:

<Redirect
  to={{
    pathname: "/test/new",
    testFunc: testFunc,
    state: { property_id: property_id }
  }}
/>
Run Code Online (Sandbox Code Playgroud)

访问 NewTestComp 中的两个 props:

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

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

<Redirect
  to={{
    pathname: "/test/new",
    testFunc: testFunc,
    propetries: { property_id: property_id1, property_id2: property_id2},
    another_prop: "another_prop"
  }}
/>
Run Code Online (Sandbox Code Playgroud)

并像这样访问:

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);
Run Code Online (Sandbox Code Playgroud)