Javascript 从vanilla JS调用React路由器

Javascript 从vanilla JS调用React路由器,javascript,reactjs,react-router,url-routing,Javascript,Reactjs,React Router,Url Routing,我有一个使用react路由器的react单页应用程序,并使用链接定义路径,如下所示: <Link to="second" className="level-2" params={{id:item.content}} title={item.name}>{item.name}<br/></Link> {item.name} 这会将url从/myapp/firsturi更改为/myapp/seconduri 我是否可以使用vanilla JS执行相同的rea

我有一个使用react路由器的react单页应用程序,并使用链接定义路径,如下所示:

 <Link to="second" className="level-2" params={{id:item.content}} title={item.name}>{item.name}<br/></Link>
{item.name}
这会将url从/myapp/firsturi更改为/myapp/seconduri

我是否可以使用vanilla JS执行相同的react路由器操作?我尝试使用history.pushState()和history.replaceState(),但尽管url更新正确,页面上的内容却没有。我可以使用window.location.href=“/myapp/seconduri”获得相同的结果,但这会导致页面刷新,这不是我想要的


你知道怎么做吗?

React路由器依靠
历史
模块来处理位置。页面加载时会解析初始URL,这就是设置
window.location.href
有效的原因

您使用的历史记录包括一个
listen
功能,路由器使用该功能侦听位置更改。当发生这种情况时,它将触发新位置与路由的重新匹配,从而呈现正确的组件


手动调用
pushState
/
replaceState
不会触发监听功能,这就是应用程序无法更新的原因。相反,您应该使用您的历史实例来响应。

路由器依赖
历史
模块来处理位置。页面加载时会解析初始URL,这就是设置
window.location.href
有效的原因

您使用的历史记录包括一个
listen
功能,路由器使用该功能侦听位置更改。当发生这种情况时,它将触发新位置与路由的重新匹配,从而呈现正确的组件


手动调用
pushState
/
replaceState
不会触发监听功能,这就是应用程序无法更新的原因。相反,您应该使用您的历史记录实例来。

这对我来说很有效:

// simulate navigation to where you want to be (changes URL but doesn't navigate)
window.history.pushState("","","/url");
// simulate navigation again so that
window.history.pushState("","","/url");
// when you simulate back, the router tries to get BACK to "/url"
window.history.go(-1);

我尝试的所有其他方法都只是强迫DOM再次重新加载,就像是单击链接一样。

这对我很有效:

// simulate navigation to where you want to be (changes URL but doesn't navigate)
window.history.pushState("","","/url");
// simulate navigation again so that
window.history.pushState("","","/url");
// when you simulate back, the router tries to get BACK to "/url"
window.history.go(-1);
我尝试的所有其他方法都只是强迫DOM再次重新加载,就像单击链接一样