mirror of
https://github.com/facebook/react.git
synced 2025-11-01 09:12:30 +00:00
changes as requested
This commit is contained in:
@@ -11,9 +11,9 @@ next: dom-event-listeners.html
|
||||
>
|
||||
> This isn't really a React-specific tip, as such anti-patterns often occur in code in general; in this case, React simply points them out more clearly.
|
||||
|
||||
Using props, passed down from parent, to generate state in `getInitialState` often leads to duplication of "source of truth", i.e. where the real data is (see [denormalization](http://en.wikipedia.org/wiki/Denormalization)). Whenever possible, compute values on-the-fly to ensure that they don't get out of sync later on and cause maintenance trouble. Javascript is plently fast for most use cases.
|
||||
Using props, passed down from parent, to generate state in `getInitialState` often leads to duplication of "source of truth", i.e. where the real data is. Whenever possible, compute values on-the-fly to ensure that they don't get out of sync later on and cause maintenance trouble.
|
||||
|
||||
Bad example:
|
||||
**Bad example:**
|
||||
|
||||
```js
|
||||
/** @jsx React.DOM */
|
||||
@@ -61,15 +61,15 @@ var MessageBox = React.createClass({
|
||||
React.renderComponent(<MessageBox name="Rogers"/>, mountNode);
|
||||
```
|
||||
|
||||
**But** in situations where your component truly is stateful, using props to initialize that state is totally fine. In such cases, it can be helpful to name the prop `initialX` (or similar) to make it clear that the state will not stay in sync.
|
||||
|
||||
For example:
|
||||
However, it's **not** an anti-pattern if you intentionally make it clear that synchronization's not the goal here:
|
||||
|
||||
```js
|
||||
/** @jsx React.DOM */
|
||||
|
||||
var Counter = React.createClass({
|
||||
getInitialState: function() {
|
||||
// naming it initialX clearly indicates that the only purpose
|
||||
// of the passed down prop is to initialize something internal
|
||||
return {count: this.props.initialCount};
|
||||
},
|
||||
handleClick: function() {
|
||||
@@ -78,11 +78,7 @@ var Counter = React.createClass({
|
||||
});
|
||||
},
|
||||
render: function() {
|
||||
return (
|
||||
<div onClick={this.handleClick}>
|
||||
{this.state.count}
|
||||
</div>
|
||||
);
|
||||
return <div onClick={this.handleClick}>{this.state.count}</div>;
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user