|
| 1 | +# Prevent usage of setState in componentWillUpdate (no-will-update-set-state) |
| 2 | + |
| 3 | +Updating the state during the componentWillUpdate step can lead to indeterminate component state and is not allowed. |
| 4 | + |
| 5 | +## Rule Details |
| 6 | + |
| 7 | +The following patterns are considered warnings: |
| 8 | + |
| 9 | +```jsx |
| 10 | +var Hello = React.createClass({ |
| 11 | + componentWillUpdate: function() { |
| 12 | + this.setState({ |
| 13 | + name: this.props.name.toUpperCase() |
| 14 | + }); |
| 15 | + }, |
| 16 | + render: function() { |
| 17 | + return <div>Hello {this.state.name}</div>; |
| 18 | + } |
| 19 | +}); |
| 20 | +``` |
| 21 | + |
| 22 | +The following patterns are not considered warnings: |
| 23 | + |
| 24 | +```jsx |
| 25 | +var Hello = React.createClass({ |
| 26 | + componentWillUpdate: function() { |
| 27 | + this.props.prepareHandler(); |
| 28 | + }, |
| 29 | + render: function() { |
| 30 | + return <div>Hello {this.props.name}</div>; |
| 31 | + } |
| 32 | +}); |
| 33 | +``` |
| 34 | + |
| 35 | +```jsx |
| 36 | +var Hello = React.createClass({ |
| 37 | + componentWillUpdate: function() { |
| 38 | + this.prepareHandler(function callback(newName) { |
| 39 | + this.setState({ |
| 40 | + name: newName |
| 41 | + }); |
| 42 | + }); |
| 43 | + }, |
| 44 | + render: function() { |
| 45 | + return <div>Hello {this.props.name}</div>; |
| 46 | + } |
| 47 | +}); |
| 48 | +``` |
| 49 | + |
| 50 | +## Rule Options |
| 51 | + |
| 52 | +```js |
| 53 | +... |
| 54 | +"no-will-update-set-state": [<enabled>, <mode>] |
| 55 | +... |
| 56 | +``` |
| 57 | + |
| 58 | +### `disallow-in-func` mode |
| 59 | + |
| 60 | +By default this rule forbids any call to `this.setState` in `componentWillUpdate` outside of functions. The `disallow-in-func` mode makes this rule more strict by disallowing calls to `this.setState` even within functions. |
| 61 | + |
| 62 | +The following patterns are considered warnings: |
| 63 | + |
| 64 | +```jsx |
| 65 | +var Hello = React.createClass({ |
| 66 | + componentDidUpdate: function() { |
| 67 | + this.setState({ |
| 68 | + name: this.props.name.toUpperCase() |
| 69 | + }); |
| 70 | + }, |
| 71 | + render: function() { |
| 72 | + return <div>Hello {this.state.name}</div>; |
| 73 | + } |
| 74 | +}); |
| 75 | +``` |
| 76 | + |
| 77 | +```jsx |
| 78 | +var Hello = React.createClass({ |
| 79 | + componentDidUpdate: function() { |
| 80 | + this.prepareHandler(function callback(newName) { |
| 81 | + this.setState({ |
| 82 | + name: newName |
| 83 | + }); |
| 84 | + }); |
| 85 | + }, |
| 86 | + render: function() { |
| 87 | + return <div>Hello {this.state.name}</div>; |
| 88 | + } |
| 89 | +}); |
| 90 | +``` |
0 commit comments