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

javascript - React-router and iframe, browser history - Stack Overflow

programmeradmin2浏览0评论

I came to the kind of anyoing problem. So, I have a component in react and also using react-router. Everything works almost great. This component has a list of items, when you click on one, it pushes url to the iframe[src={url}]. And here appears the problem, if I will click on several items and then click on the previous page/back button, instead of going to the previous page, it just shows the previous iframe of url that was pushed to iframe.

What do I do in this situation?

@I'm using react-router-dom v4

I came to the kind of anyoing problem. So, I have a component in react and also using react-router. Everything works almost great. This component has a list of items, when you click on one, it pushes url to the iframe[src={url}]. And here appears the problem, if I will click on several items and then click on the previous page/back button, instead of going to the previous page, it just shows the previous iframe of url that was pushed to iframe.

What do I do in this situation?

@I'm using react-router-dom v4

Share Improve this question edited Oct 25, 2017 at 7:23 Suresh Ponnukalai 14k5 gold badges35 silver badges54 bronze badges asked Jul 24, 2017 at 9:44 bunakawakabunakawaka 5551 gold badge6 silver badges15 bronze badges 2
  • do the buttons change the url of the main window page? – Hitmands Commented Jul 24, 2017 at 9:47
  • You mean, when I push the url to iframe? No, url stays the same. – bunakawaka Commented Jul 24, 2017 at 9:47
Add a comment  | 

2 Answers 2

Reset to default 14

Don't just change the src. You've to replace a new iframe everytime the src change. By doing that without change things much, just add difference key to your iframe everytime you change src

render() {
  const iframe = <iframe key={this.thing.id} src={this.thing.src} />;
  return iframe;
}

Just to add to @Expl0de answer,

You should add a unique value to the key attribute, which will change from src to src, each time the iframe is reused.

The issue happens because an iframe changing the src attribute is considered as content navigation, being pushed to the window.history browser stack. When you go back in the browser navigation it just loads the same page, same iframe with a different src attribute.

When adding a key prop that changes on different src values, React will unmount and remount this iframe element, because it is not the "same element" anymore. This will prevent the iframe from changing the browser's history.

A more in-depth explanation, covering React's Reconciliation Process and examples, can be found here: https://www.aleksandrhovhannisyan.com/blog/react-iframes-back-navigation-bug/

发布评论

评论列表(0)

  1. 暂无评论