ReactJS - 使用重定向组件传递道具



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

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

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

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

这是您可以访问它的方式:

this.props.location.state.id

API 文档解释了如何在重定向/历史记录属性中传递状态和其他变量。

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

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

<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);}

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

<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

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

使用 Kumar @Barat答案,在这里您还可以看到如何使用重定向将函数作为道具传递和访问。请注意,您访问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出发,您可以:

<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);
<Redirect to={{
pathname: '/path',
state: { id: '123' }
}} />

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

  • 您可以出于相同的目的使用自己的钩子:
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>

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

最新更新