[英]How do you pass data when using the navigate function in react router v6
In v4 you would do a history.push('/whatever', { data }) Then the component tied to that route could read the data object by referencing the history.location.state在 v4 中,您将执行 history.push('/whatever', { data }) 然后绑定到该路由的组件可以通过引用 history.location.state 读取数据 object
Now with v6 that's changed to navigate('whatever')现在 v6 已更改为 navigate('whatever')
How do you pass data like before?你如何像以前一样传递数据?
It's similar to how it's done in v4, two arguments, the second being an object with a state
property.它与 v4 中的做法类似,有两个参数,第二个是具有
state
属性的对象。
navigate(
'thepath',
{
state: {
//...values
}
}
})
From the migration guide: Use navigate instead of history来自迁移指南: 使用导航而不是历史记录
If you need to replace the current location instead of push a new one onto the history stack, use
navigate(to, { replace: true })
.如果您需要替换当前位置而不是将新位置推入历史堆栈,请使用
navigate(to, { replace: true })
。 If you need state, usenavigate(to, { state })
.如果您需要状态,请使用
navigate(to, { state })
。 You can think of the first arg to navigate as your and the other arg as thereplace
andstate
props.您可以将要导航的第一个 arg 视为您的,而将另一个 arg 视为
replace
和state
道具。
To access the route state in the consuming component use the useLocation
React hook:要访问消费组件中的路由状态,请使用
useLocation
React 钩子:
const { state } = useLocation();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.