[英]React: How to redirect to new route (different id) from same route?
In react-router,
we cannot push the same route in useHisotry()
and cause a re-render.在react-router,
我们不能在useHisotry()
中推送相同的路由并导致重新渲染。 Eg, if component App is showing on route https://localhost:3000
and I click the button Click Me!
例如,如果组件 App 显示在路线https://localhost:3000
上,我单击按钮Click Me!
, it won't cause a re-render: ,它不会导致重新渲染:
function App() {
const history = useHistory();
return (
<button onClick={() => {history.push('/')}}> Click Me! </button>
)
}
I want to achieve similar functionality, but I am unsure about the approach or what I am missing.我想实现类似的功能,但我不确定这种方法或我缺少什么。
My current route looks like this: https://localhost:3000/user/1我当前的路线如下所示: https://localhost:3000/user/1
I want to go to user/2 by clicking a button.我想通过单击按钮将 go 发送给user/2 。
My code looks like the below:我的代码如下所示:
<Route exact path="/user/:userId" component={User} />
function User() {
const history = useHistory();
return (
<button onClick={() => {history.push('/user/2')}}> Click Me! </button>
)
}
The above code changes the route but doesn't re-render the component.上面的代码更改了路由,但没有重新渲染组件。 How can I fix this issue?我该如何解决这个问题?
Thanks谢谢
My advice is to upgrade to react router dom v6
and use useNavigate
, tutorial here我的建议是升级到react router dom v6
并使用useNavigate
,教程在这里
once you import useNavigate
from react-router-dom
一旦你从react-router-dom
导入useNavigate
let navigate = useNavigate();
and on your button you call this function on click passing your desired url
并在您的按钮上调用此 function 点击传递您想要的url
<button onClick={()=> navigate('/users/2')}
I don't recommend using history
for this case.我不建议在这种情况下使用history
。 If you really need to, inside User
component get userId parameter and react on that.如果您确实需要,请在User
组件内部获取 userId 参数并对此做出反应。
<Route exact path='/user/:userId' component={User} />
const User = () => {
const { userId } = useParams();
return (
<div>userId: { userId }</div>
);
}
export default User;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.