[英]How to migrate useHistory.replace(x, y) with useNavigate in react-router v6?
I'm upgrading react-router-dom from v5 to v6 in a codebase I'm not entirely familiar with yet, and I am curious about how to replace the following code:我在一个我还不完全熟悉的代码库中将 react-router-dom 从 v5 升级到 v6,我很好奇如何替换以下代码:
const history = useHistory();
history.replace(url, params);
In the docs they only display what you would do to replace in case there's 1 argument.在文档中,它们仅显示在有 1 个参数的情况下您要替换的内容。 so if I had:
所以如果我有:
history.replace(url)
I'd simply do:我只是这样做:
const navigate = useNavigate();
navigate(url, {replace: true})
How do I ensure the second argument is kept with the useNavigate hook?如何确保第二个参数与 useNavigate 挂钩?
I'm tempted to do this:我很想这样做:
const navigate = useNavigate();
navigate(url, params)
or或者
const navigate = useNavigate();
navigate(url, { state: params })
How should it be replaced without any impacts?应该如何更换才不会造成影响?
The state is sent in the second parameter under the state
property, same as indicating a redirect (REPLACE) vs navigate (PUSH).状态在
state
属性下的第二个参数中发送,与指示重定向 (REPLACE) 与导航 (PUSH) 相同。
The useNavigate
hook returns a navigate
function: useNavigate
钩子返回一个navigate
函数:
declare function useNavigate(): NavigateFunction; interface NavigateFunction { ( to: To, options?: { replace?: boolean; state?: any } ): void; (delta: number): void; }
Note that the second argument is an options
arg with replace
and state
properties.请注意,第二个参数是具有
replace
和state
属性的options
arg。
Action![]() |
v5 ![]() history = useHistory() |
v6 ![]() navigate = useNavigate() |
---|---|---|
Navigate![]() |
history.push(url) |
navigate(url) |
Redirect![]() |
history.replace(url) |
navigate(url, { replace: true }) |
Navigate w/state![]() |
history.push(url, params) |
navigate(url, { state: params }) |
Redirect w/state![]() |
history.replace(url, params) |
navigate(url, { replace: true, state: params }) |
navigate(url, params)
would only work if params
is an object with replace
and/or state
properties, eg { replace: true, state: { ... } }
. navigate(url, params)
仅在params
是具有replace
和/或state
属性的对象时才有效,例如{ replace: true, state: { ... } }
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.