state
React data is divided into two components: props
and state
, props
a component of the external interface, state
the internal state of the component. State state
and property props
is very similar, but the state is private, fully controlled by the current component, whether props
or state
changes may trigger re-rendering components.
Because React
not directly modify incoming props
, so the need to record their own data changes, it is necessary to use state
.
Components state
equivalent to the components of memory, its raison d'etre is to be changed, each time by this.setState
function modified state
to change the state of the component, and then through the rendering process reflected this change.
Proper use [state]
1, do not directly update the state, it is the only constructor to initialize this.state
place.
If you directly modify the value this.state, although in fact changed the internal state of the component, but only modify the savage state, but did not drive assembly is re-rendered. And this.setState()
what function it does is to change the this.state
value, and then re-render the drive assembly.
// Wrong
this.state.comment = 'Hello';
// Correct
this.setState({comment: 'Hello'});
2, the status updates may be asynchronous to
setState
asynchronous updates, rather than updating the synchronization, the following is an example.
setYear(){
let {year} = this.state
this.setState({
year: year + 10 //新值
})
console.log(this.state.year)//旧值
}
setYear(){
setTimeout(() => {
this.setState({
year: year + 10 //新值
})
console.log(this.state.year)//新值
})
}
Because this.props
and this.state
may be updated asynchronously, you should not rely on their values to calculate the next state.
// Wrong
this.setState({
counter: this.state.counter + this.props.increment,
});
To fix it, use the second form setState()
to accept a function rather than an object. The function received a previous state as the first parameter, the update is applied props
as the second argument:
// Correct
this.setState((prevState, props) => ({
counter: prevState.counter + props.increment
}));
3, combined update
can be invoked setState()
independently update them, but React multiple setState()
calls into a call combined to improve performance.
componentDidMount() {
fetchPosts().then(response => {
this.setState({
posts: response.posts
});
});
fetchComments().then(response => {
this.setState({
comments: response.comments
});
});
}
Merger here is shallow merger, that this.setState({comments})
retained the integrity of this.state.posts
, but completely replaced this.state.comments
.
4, the callback function
due to the setState
asynchronous update, if necessary determined setState
after the update, and then perform certain operations, can use setState
a callback function.
this.setState({ val:value }, () => {
this.refs.editInput.focus()
})