Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use forceUpdate() correctly? [duplicate]

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

});

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

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

like image 931
Kaitlyn Avatar asked Jan 10 '17 23:01

Kaitlyn


People also ask

What is the use of forceUpdate () method?

forceUpdate() This will trigger the normal lifecycle methods for child components, including the shouldComponentUpdate() method of each child. React will still only update the DOM if the markup changes. Normally you should try to avoid all uses of forceUpdate() and only read from this.props and this.state in render() .

Is there something like forceUpdate?

Is there something like forceUpdate? Both useState and useReducer Hooks bail out of updates if the next value is the same as the previous one. Mutating state in place and calling setState will not cause a re-render.

How do you use forceUpdate in React native?

Forcing an update on a React class component In any user or system event, you can call the method this. forceUpdate() , which will cause render() to be called on the component, skipping shouldComponentUpdate() , and thus, forcing React to re-evaluate the Virtual DOM and DOM state.


1 Answers

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')
);
like image 160
zloctb Avatar answered Sep 29 '22 02:09

zloctb