ReactJS-通过Redirect组件传递道具

时间:2018-08-28 18:34:44

标签: javascript reactjs react-router-dom

如何在Redirect组件中传递道具而又不将它们暴露在URL中?

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

5 个答案:

答案 0 :(得分:30)

您可以像这样通过Redirect传递数据:

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

这是您可以使用的方式:

this.props.location.state.id

在重定向/历史记录属性中用于传递状态和其他变量的API dcoumentation

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

答案 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

进行访问

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

答案 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在所需组件中访问它

相关问题