如何在Redirect
组件中传递道具而又不将它们暴露在URL中?
喜欢这个<Redirect to="/order?id=123 />"
吗?我正在使用react-router-dom
。
答案 0 :(得分:30)
您可以像这样通过Redirect
传递数据:
<Redirect to={{
pathname: '/order',
state: { id: '123' }
}}
/>
这是您可以使用的方式:
this.props.location.state.id
在重定向/历史记录属性中用于传递状态和其他变量的API dcoumentation。
答案 1 :(得分:22)
您应该首先在您在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);}
答案 2 :(得分:8)
您可以使用以下浏览器历史记录状态:
<Redirect to={{
pathname: '/order',
state: { id: '123' }
}} />
然后您可以通过this.props.location.state.id
答案 3 :(得分:0)
import { createBrowserHistory } from "history";
const withRefresh = createBrowserHistory({ forceRefresh: true });
const ROOT_PATH = process.env.PUBLIC_URL || "/myapp";
const useRedirectToAccounting = (params="1") => {
if(params){
withRefresh.push({
pathname: `${ROOT_PATH}/create`,
state: { id: `${params}` }
});
}
}
export default redirectToAccounting;
import useRedirectToAccounting from './redirectToAccounting
const handleOnClick = params => useRedirectToAccounting(params)
const RedirectorComponent = () => <a onClick={handleOnClick}>{"Label"}</a>
**这可以根据需要进一步重构。
答案 4 :(得分:0)
<Redirect to={{
pathname: '/path',
state: { id: '123' }
}} />
然后您可以通过this.props.location.state.id
在所需组件中访问它