如何正确使用 forceUpdate()?

IT技术 javascript reactjs iframe
2021-05-11 06:26:44

我正在尝试定期重新加载 iframe,但我使用的是 React,因此我无法直接操作 DOM。似乎我最好的选择是使用 forceUpdate(),因为 url 没有改变,所以我不能使用状态更改来更新它(请参阅上一篇文章:使用 React 定期重新加载 iframe 的最佳方法是什么?)。但是,当我尝试执行 forceUpdate() 时,它不会重新渲染我的组件。关于为什么的任何想法?

var Graph = React.createClass({
componentDidMount: function() {
    setInterval(function(){
        this.forceUpdate();
    }.bind(this), 5000);
},
render() {
    return (
        <iframe src="http://play.grafana.org/dashboard/db/elasticsearch-metrics" width="1900px" height="700px"/>
    )
}

});

在此处查看代码笔:http ://codepen.io/anon/pen/ggPGPQ

**我知道可以将 grafana 设置为自动更新,我只是将其用作 iframe 示例。

2个回答
class App extends React.Component {
    state = {
        name: 'request',
        phones: ['nokia', 'sonya', 'ericsson']
    }

     Rerender = () => {
        this.forceUpdate()
     }

    render() {
        const rd= Math.random();
        return ( <div> REACT APP
            { this.state.phones.map(item => <p>{item} {rd}</p>) }

            <input type="button" value="Click" onClick={this.Rerender}/>
        </div>)
    }
}
ReactDom.render(
        <App />,
    document.getElementById('root')
);

React 很聪明地知道该元素没有改变,所以它不会在重新渲染时卸载它。有很多方法可以删除元素并将其添加回来,但这里是基于您的示例构建的一种人为方法(在每个时间间隔渲染两次以删除并添加回 iframe):

var Graph = React.createClass({
    getInitialState: function() {
      return {count: 0};
    },
    componentDidMount: function() {
        setInterval(function(){
            this.setState({count: this.state.count + 1});
            this.setState({count: this.state.count + 1});
        }.bind(this), 5000);
    },
    render() {
        return this.state.count % 2 === 0 ? (
          <iframe src="http://play.grafana.org/dashboard/db/elasticsearch-metrics" width="1900px" height="700px"/>
        ) : null;
    }
});

ReactDOM.render((
    <div style={{height:'100%'}}>
        <Graph />
    </div>
), document.getElementById('root'));