【问题标题】:change value of this.props.location.state in react route在反应路线中更改 this.props.location.state 的值
【发布时间】:2021-09-08 06:10:06
【问题描述】:
网上有很多类似如下代码的例子:
const { state } = this.props.location;
window.location = state ? state.from.pathname : "/dashboards/index";
如何更改源类中的 this.props.location.state 并传递到目标?
我的问题是,如果我想使用路由从一个页面(类组件)转到另一个页面,如何更改 this.props.location.state 的值并将其传递给目标组件?
我的场景是,当有人进入受保护的页面并重定向到登录页面时,身份验证后返回到请求的页面。通过更改 this.props.location.state 的值?
【问题讨论】:
标签:
reactjs
react-router
state
【解决方案1】:
我不确定你在问什么,但正如我所想的那样,你想在推送到路由时添加状态。如果是这样,那么这应该可以在class components
this.props.history.push({
pathname: '/template',
search: '?query=something',
state: { key: value }
})
在functional components 中你可以使用钩子,useHistory
const { push } = useHistory();
push(path, [state])
您可以通过
in class components
访问刚刚在目标路由中传递的状态
this.props.location.state.key
in functional components
const { state } = useLocation();
state.key
【解决方案2】:
不要改变这个对象。你不应该!!
如果你想在页面之间重定向,那么你可以使用:
this.props.history.push("/path-to-navigate")