Rendering with state or props

I would like to know the difference between a stateful or props rendering component directly.

getInitialState:
    data: this.props.data

      

The following code is for the render function

1.

data = this.state.data
return (<Component data={data} />)

      

2.

return (<Component data={this.state.data} />)

      

3.

return (<Component data={this.props.data} />)

      

The first two situations fail when I use setState while listening for reflux. If anyone has any usage guidelines other than setState, or tell me that the difference in these 3 pieces of code would be much appreciated.

+3


source to share


2 answers


Place props in a state like this:

getInitialState: function () {
  return {
    someKey: this.props.someKey
  };
}

      

is an anti-pattern, unless you intend to change the value someKey

later and you use prop as soon as the initial value.



So, if you don't change the skipped pass value, you should go with number three.

The difference is that a component that is stateless can be considered "clean" (the same props passed at each point in time produce the same result), and these components are almost always easier to reason about. Duplicating support in a stateless state just gives you more lines of code in a component, and it might confuse someone else reading the code. It is a pure component disguised as an impure component.

+6


source


A bit more about props and states. Support and state are linked. The state of one component often becomes the pivot of the child component. The props are passed to the child in the parent's render method as the second argument to React.createElement () or, if you're using JSX, the more familiar tag attributes.

<MyChild name={this.state.childsName} />

      

The value of the parent state childsName becomes the child of this.props.name. From a child's point of view, the name prop is immutable. If this needs to be changed, the parent should simply change its internal state:

this.setState({ childsName: 'New name' });

      



and React will propagate it to the child for you. The natural next question is: what if the child needs to change his name? This is usually done through child events and parent callbacks. The child can expose an event called onNameChanged, for example. The parent will then subscribe to the event by passing in a callback handler.

<MyChild name={this.state.childsName} onNameChanged={this.handleName} />

      

The child would pass the new name to it as an argument for the event callback, for example calling this.props.onNameChanged ('New name'), and the parent would use that name in the event handler to update their state.

handleName: function(newName) {
   this.setState({ childsName: newName });
}

      

+2


source







All Articles