【发布时间】:2019-02-03 11:12:33
【问题描述】:
你应该如何通过 Redirect 组件传递道具而不让它们暴露在 url 中?
喜欢这个<Redirect to="/order?id=123 />"?我正在使用react-router-dom。
【问题讨论】:
标签: javascript reactjs react-router-dom
你应该如何通过 Redirect 组件传递道具而不让它们暴露在 url 中?
喜欢这个<Redirect to="/order?id=123 />"?我正在使用react-router-dom。
【问题讨论】:
标签: javascript reactjs react-router-dom
您可以像这样使用浏览器历史状态:
<Redirect to={{
pathname: '/order',
state: { id: '123' }
}} />
然后你可以通过this.props.location.state.id访问它
【讨论】:
withRouter 包装你的组件
Expected an assignment or function call and instead saw an expression。有什么建议吗?
您可以像这样使用Redirect 传递数据:
<Redirect to={{
pathname: '/order',
state: { id: '123' }
}}
/>
您可以通过以下方式访问它:
this.props.location.state.id
API docs 解释了如何在 Redirect / History 属性中传递状态和其他变量。
【讨论】:
pathname、search、state 等,它们是浏览器历史记录使用的值。任何自定义值都应包含在下一层的state 对象中。它更干净,并将浏览器历史记录使用的内容与您自己的自定义对象分开。
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>
** 这可以根据需求进一步重构。
【讨论】:
您应该首先在您在 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);}
【讨论】:
<Redirect to={{
pathname: '/path',
state: { id: '123' }
}} />
然后你可以通过所需组件中的this.props.location.state.id访问它
【讨论】:
使用功能组件/钩子,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);
【讨论】: