Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react.js ReactComponent does not offer setState()?

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?

like image 869
ghost23 Avatar asked Sep 11 '14 15:09

ghost23


People also ask

Why putting setState () in render () is not preferred?

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.

How do I use setState in React JS?

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.

Can we use setState in shouldComponentUpdate?

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 .

Can we call setState in componentDidUpdate?

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.


1 Answers

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
like image 127
Felix Kling Avatar answered Sep 19 '22 14:09

Felix Kling