如何正确使用forceUpdate()? [英] How to use forceUpdate() correctly?

查看:1445
本文介绍了如何正确使用forceUpdate()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to periodically reload an iframe but i'm using React so i can't manipulate the DOM directly. It seems like my best option is to use forceUpdate() because the url isn't changing so i can't use a state change to update it (See previous post here What's the best way to periodically reload an iframe with React?). However when i try doing a forceUpdate() it doesn't re-render my component. Any ideas as to why?

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"/>
    )
}

});

请参阅此处的codepen: http://codepen.io/anon/pen/ggPGPQ

See the codepen here: http://codepen.io/anon/pen/ggPGPQ

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

**I know grafana can be set to auto update, i'm just using this as an example iframe.

推荐答案

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

React is intelligent to know that that element hasn't changed so it doesn't unmount it on rerender. There are many ways you can remove the element and add it back but here is one contrived way built on your example (renders twice on each interval to remove and add back the 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'));

这篇关于如何正确使用forceUpdate()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆