Javascript ReactJS - 使用重定向组件传递道具
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/52064303/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ReactJS - Pass props with Redirect component
提问by Michiel
How should you pass props with the Redirectcomponent without having them exposed in the url? 
你应该如何通过Redirect组件传递 props而不让它们暴露在 url 中?
Like this <Redirect to="/order?id=123 />"? I'm using react-router-dom.
像这样<Redirect to="/order?id=123 />"?我正在使用react-router-dom.
回答by Sakhi Mansoor
You can pass data with Redirectlike this:
您可以Redirect像这样传递数据:
<Redirect to={{
            pathname: '/order',
            state: { id: '123' }
        }}
/>
and this is how you can access it:
这是您访问它的方式:
this.props.location.state.id
The API docsexplain how to pass state and other variables in Redirect / History prop.
该API文档解释了如何通过状态和其他变量重定向/历史道具。
来源:https: //github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/Redirect.md#to-object
回答by Anas
You can use browser history state like this:
您可以像这样使用浏览器历史记录状态:
<Redirect to={{
    pathname: '/order',
    state: { id: '123' }
}} />
Then you can access it via this.props.location.state.id
然后你可以通过访问它 this.props.location.state.id
来源:https: //github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/Redirect.md#to-object
回答by Barat Kumar
You should first pass the props in Route where you have define in your App.js
您应该首先在 App.js 中定义的 Route 中传递道具
<Route path="/test/new" render={(props) => <NewTestComp {...props}/>}/>
then in your first Component
然后在你的第一个组件中
<Redirect
            to={{
            pathname: "/test/new",
            state: { property_id: property_id }
          }}
        />
and then in your Redirected NewTestComp you can use it where ever you want like this
然后在您的 Redirected NewTestComp 中,您可以像这样在任何地方使用它
componentDidMount(props){
console.log("property_id",this.props.location.state.property_id);}
回答by Ashif Zafar
- You can come with your own hook for the same purpose :
- 你可以带着你自己的钩子来达到同样的目的:
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;
- and use it like :
- 并像这样使用它:
 import useRedirectToAccounting from  './redirectToAccounting
const handleOnClick = params => useRedirectToAccounting(params)
const RedirectorComponent = () => <a onClick={handleOnClick}>{"Label"}</a>
** this can be further refactored based on requirement.
** 这可以根据需求进一步重构。

