使用 React 定期重新加载 iframe 的最佳方法是什么?

IT技术 javascript reactjs iframe
2021-04-26 01:34:48

我正在使用 React 构建网页,这意味着我无法直接操作 DOM。我尝试通过更新 url 状态来重新加载 iframe,但这似乎并没有重新加载页面。这是我尝试过的状态代码。

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} />
    )
}
2个回答

更改组件的关键属性,例如:

this.state = {iframeKey: 0};

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

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

这是ref属性的一个用例,如果我认为 iframe 的内容不受react控制。将一个应用到 iframe,然后使用 setInterval 刷新 iframe url。

当您将 URL 设置为 state 时 iframe 没有更新的原因是 URL 没有更改(?)并且在这种情况下 react 不会重绘。