最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Calling React Router from vanilla JS - Stack Overflow

programmeradmin2浏览0评论

I have a react single page application using React Router, and having paths defined using Link as shown below:

 <Link to="second" className="level-2" params={{id:item.content}} title={item.name}>{item.name}<br/></Link>

This changes url from /myapp/firsturi to /myapp/seconduri

Is it possible for me to make the same react router action using vanilla JS? I tried using history.pushState() and history.replaceState() but while the url updates correctly, the content on the page does not. I can get the same thing using window.location.href="/myapp/seconduri" but that causes a page refresh which is not what I want.

Any idea how to go about this?

I have a react single page application using React Router, and having paths defined using Link as shown below:

 <Link to="second" className="level-2" params={{id:item.content}} title={item.name}>{item.name}<br/></Link>

This changes url from /myapp/firsturi to /myapp/seconduri

Is it possible for me to make the same react router action using vanilla JS? I tried using history.pushState() and history.replaceState() but while the url updates correctly, the content on the page does not. I can get the same thing using window.location.href="/myapp/seconduri" but that causes a page refresh which is not what I want.

Any idea how to go about this?

Share Improve this question edited Jun 18, 2017 at 7:43 laser 1,37613 silver badges14 bronze badges asked Nov 24, 2016 at 8:24 navinpainavinpai 99514 silver badges36 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

This has worked for me:

// 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);

Everything else I tried was just forcing the DOM to reload again as if it was a link click.

React Router relies on the history module to handle locations. When the page loads it parses the initial URL, which is why setting window.location.href works.

The history that you use includes a listen function which React Router uses to listen for location changes. When one occurs, it will trigger a re-matching of the new location against your routes, which in turn will render the correct ponents.

Manually calling pushState/replaceState does not trigger the listening function, which is why your app is failing to update. Instead, you should use your history instance to navigate.

发布评论

评论列表(0)

  1. 暂无评论