I seem to misunderstand some fundamental parts of React.js.
In http://facebook.github.io/react/docs/component-api.html
it says, that a react component has methods like setState().
But when I do this:
var MyComp = React.createClass({
getInitialState: function() {
return {dummy: "hello"};
},
render: function() { return React.DOM.h1(null, this.state.dummy + ", world!") }
}
var newComp = MyComp(null);
React.renderComponent(newComp, myDomElement);
MyComp.setState({dummy: "Good Bye"}); // Doesn't work. setState does not exist
newComp.setState({dummy: "Good Bye"}); // Doesn't work either. setState does not exist
There is no setState() method to be found. But in the docs it says Component API, so what am I getting wrong here?
The render() function should be pure, meaning that it does not modify a component's state. It returns the same result each time it's invoked, and it does not directly interact with the browser. In this case, avoid using setState() here.
The setState() Method State can be updated in response to event handlers, server responses, or prop changes. This is done using the setState() method. The setState() method enqueues all of the updates made to the component state and instructs React to re-render the component and its children with the updated state.
shouldComponentUpdate() Safe to use setState ? Yes! This method is called whenever there is an update in the props or state. This method has arguments called nextProps and nextState can be compared with current props and currentState .
You may call setState() immediately in componentDidUpdate() but note that it must be wrapped in a condition like in the example above, or you'll cause an infinite loop. It would also cause an extra re-rendering which, while not visible to the user, can affect the component performance.
As per this blog post and this writeup, calling MyComp
doesn't return an instance anymore, it returns a lightweight descriptor.
Anti-pattern:
var MyComponent = React.createClass({
customMethod: function() {
return this.props.foo === 'bar';
},
render: function() {
}
});
var component = <MyComponent foo="bar" />;
component.customMethod(); // invalid use!
Correct usage:
var MyComponent = React.createClass({
customMethod: function() {
return this.props.foo === 'bar';
},
render: function() {
}
});
var realInstance = React.renderComponent(<MyComponent foo="bar" />, root);
realInstance.customMethod(); // this is valid
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With