init state without constructor in react
About the question 2, refer to Dan's great answer here: Do I need to use setState(function) overload in this case?
No it's not a local variable. It's the same as declaring
this.state
in constructor.Yes in that case you can just use
this.setState({ value: this.state.value + 1 })
, the result will be the same.
But note that by using functional setState
you can have some benefits:
the setState function can be reused if you declare it outside:
const increment = prevState => ({ value: prevState.value + 1 })
now if you have several components need to use this function, you can just import and reuse the logic everywhere.
this.setState(increment)
React squashes several
setState
and executes them in batch. This may cause some unexpected behaviors. Please see the following example:http://codepen.io/CodinCat/pen/pebLaZ
add3 () { this.setState({ count: this.state.count + 1 }) this.setState({ count: this.state.count + 1 }) this.setState({ count: this.state.count + 1 }) }
executing this function the
count
will only plus 1If you use functional setState:
http://codepen.io/CodinCat/pen/dvXmwX
const add = state => ({ count: state.count + 1 }) this.setState(add) this.setState(add) this.setState(add)
count will +3 as you expected.
You can see the docs here: https://facebook.github.io/react/docs/react-component.html#setstate
Answer to Question 1:
Yes, you can initialize state without a constructor for a React class component:
class Counter extends Component {
state = { value: 0 };
handleIncrement = () => {
this.setState(prevState => ({
value: prevState.value + 1
}));
};
handleDecrement = () => {
this.setState(prevState => ({
value: prevState.value - 1
}));
};
render() {
return (
<div>
{this.state.value}
<button onClick={this.handleIncrement}>+</button>
<button onClick={this.handleDecrement}>-</button>
</div>
)
}
}
It uses class field declarations. You can checkout the sample application over here. You can also use state in React function components (without a constructor), but using higher-order components or render prop components. You can find out more about it here.
Answer to Question 2: There are two ways to update local state in React with this.setState
. You can either use an object or a function. The object is just fine if you are not relying on props or state of the component to update its state. If you rely on props or state, you should use the function instead, because it always has the most recent props and state at the time of execution. All this is because this.setState()
is executed asynchronous, so you could use stale state or props when updating your local state with the object instead of the function. You can read more about it here.
I have 2 question, what is
state
here?
An instance property, like setting this.state = {value: 0};
in a constructor. It's using the Public Class Fields proposal currently at Stage 2. (So are increment
and decrement
, which are instance fields whose values are arrow functions so they close over this
.)
is that a local variable?
No.
where does the prevState come from? why arrow function is used in setState? isn't it's easy to just do this.setState({value:'something'})?
From the documentation:
React may batch multiple
setState()
calls into a single update for performance.Because
this.props
andthis.state
may be updated asynchronously, you should not rely on their values for calculating the next state.For example, this code may fail to update the counter:
// Wrong this.setState({ counter: this.state.counter + this.props.increment, });
To fix it, use a second form of
setState()
that accepts a function rather than an object. That function will receive the previous state as the first argument, and the props at the time the update is applied as the second argument:// Correct this.setState((prevState, props) => ({ counter: prevState.counter + props.increment }));
...which is exactly what the quoted code is doing. This would be wrong:
// Wrong
increment = () => {
this.setState({
value: this.state.value + 1
});
};
...because it's relying on the state of this.state
, which the above tells us not to; so the quoted code does this instead:
increment = () => {
this.setState(prevState => ({
value: prevState.value + 1
}));
};
Here's proof that React may batch calls in a non-obvious way and why we need to use the callback version of setState
: Here, we have increment
and decrement
being called twice per click rather than once (once by the button, once by a span containing the button). Clicking +
once should increase the counter to 2, because increment
is called twice. But because we haven't used the function callback version of setState
, it doesn't: One of those calls to increment
becomes a no-op because we're using a stale this.state.value
value:
class Counter extends React.Component {
state = { value: 0 };
increment = () => {
/*
this.setState(prevState => ({
value: prevState.value + 1
}));
*/
console.log("increment called, this.state.value = " + this.state.value);
this.setState({
value: this.state.value + 1
});
};
fooup = () => {
this.increment();
};
decrement = () => {
/*
this.setState(prevState => ({
value: prevState.value - 1
}));
*/
console.log("decrement called, this.state.value = " + this.state.value);
this.setState({
value: this.state.value - 1
});
};
foodown = () => {
this.decrement();
};
render() {
return (
<div>
{this.state.value}
<span onClick={this.fooup}>
<button onClick={this.increment}>+</button>
</span>
<span onClick={this.foodown}>
<button onClick={this.decrement}>-</button>
</span>
</div>
)
}
}
ReactDOM.render(
<Counter />,
document.getElementById("react")
);
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
With the function callback, it works correctly (no calls to increment
become no-ops):
class Counter extends React.Component {
state = { value: 0 };
increment = () => {
this.setState(prevState => {
console.log("Incrementing, prevState.value = " + prevState.value);
return {
value: prevState.value + 1
};
});
};
fooup = () => {
this.increment();
};
decrement = () => {
this.setState(prevState => {
console.log("Decrementing, prevState.value = " + prevState.value);
return {
value: prevState.value - 1
};
});
};
foodown = () => {
this.decrement();
};
render() {
return (
<div>
{this.state.value}
<span onClick={this.fooup}>
<button onClick={this.increment}>+</button>
</span>
<span onClick={this.foodown}>
<button onClick={this.decrement}>-</button>
</span>
</div>
)
}
}
ReactDOM.render(
<Counter />,
document.getElementById("react")
);
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
In this case, of course, we can look at the render
method and say "Hey, increment
will get called twice during a click, I'd better use the callback version of setState
." But rather than assuming it's safe to use this.state
when determining next state, best practice is not to assume that. In a complex component, it's easy to use mutator methods in a way that the author of the mutator method may not have thought of. Hence the statement by the React authors:
Because
this.props
andthis.state
may be updated asynchronously, you should not rely on their values for calculating the next state.