What's the best way to periodically reload an iframe with React?

早过忘川 提交于 2020-01-11 12:37:13

问题


I'm building a webpage using React which means I can't manipulate the DOM directly. I've tried reloading my iframe by updating the url state but that doesn't seem to reload the page. This is the state code I have tried.

componentDidMount: function() {
    setInterval(function(){
        this.setState({currentUrl:currentUrl});
    }.bind(this), 1000);
},
 getInitialState: function() {
    return {defaultUrl:this.props.graph.url, currentUrl:this.props.graph.url};
},
render() {
    // render the graph iframe
    return (
        <iframe src={this.state.currentUrl} id={this.props.graph.url} style={this.props.style} width={this.props.width} height={this.props.graph_height} />
    )
}

回答1:


Change key property for component for example:

this.state = {iframeKey: 0};

setInterval(() => this.setState(s => ({iframeKey: s.iframeKey + 1})), 1000);

<Iframe key={this.state.iframeKey} url={some url}/>



回答2:


This is a use case for the ref property if, as I assume, the contents of the iframe isn't under react control. Apply one to the iframe, then use the setInterval to refresh the iframe url.

The reason the iframe isn't updating when you set the URL in state is that the url hasn't changed(?) and react doesn't redraw when that's the case.



来源:https://stackoverflow.com/questions/41576794/whats-the-best-way-to-periodically-reload-an-iframe-with-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!