React路由器,以编程方式导航时传递数据? [英] React router, pass data when navigating programmatically?
问题描述
我们可以使用
this.props.router.push('/some/path')
有没有办法在导航时发送参数(对象)?
Is there a way to send params (object) along when navigating?
我还能想到其他选项,但想知道是否可以传递 object
?
There are other options I can think of, but wonder if passing object
is possible at all?
我可以嵌入对象的 id 并从服务器重新获取对象从新页面.
I could embed id of the object and refetch the object from server from the new page.
或者我可以将对象存储在像 redux store 这样的全局存储中.(这个对象需要尽快从商店中移除.所以我认为首先将它放在那里可能不太好)
Or I could store the object in global storage like redux store. (This object needs to be removed from the store soon. So I'm thinking it might not be good to put it there in the first place)
推荐答案
React Router 使用 location
对象.location
对象的属性之一是 state
.
React Router uses location
objects. One of the properties of a location
object is state
.
this.props.router.push({
pathname: '/other-page',
state: {
id: 7,
color: 'green'
}
})
在导航到的页面上,当前的location
会被注入到路由匹配的组件中,这样你就可以使用this.props.location.state来访问状态代码>.
On the page that is navigated to, the current location
will be injected into the component whose route matched, so you can access the state using this.props.location.state
.
要记住的一点是,如果用户直接导航到页面,则不会有 state
,因此当数据不存在时,您仍然需要某种机制来加载数据.
One thing to keep in mind is that there will be no state
if a user navigates directly to the page, so you will still need some mechanism to load the data when it does not exist.
这篇关于React路由器,以编程方式导航时传递数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!