目录
1:使用对象形式的setState
:
this.setState({ count: 0 });
2:使用函数形式的setState
:
this.setState((prevState,props) => {
return { count: prevState.count + 1 };
});
3:使用回调函数:
this.setState({ count: this.state.count + 1 }, () => {
console.log('状态已更新,组件已重新渲染');
});
完整示例:
import React, { Component } from 'react';
class Counter extends Component {
constructor(props) {
super(props);
this.state = {
count: 0,
};
}
increment = ()=> {
// 使用对象形式的 setState
this.setState({
count: this.state.count + 1
});
// 使用函数形式的 setState
this.setState((prevState,props) => {
console.log(prevState.count)
console.log(props)
return { count: prevState.count + 1 };
});
// 使用回调函数
this.setState({
count: this.state.count + 1
},
() => {
console.log('状态已更新,组件已重新渲染');
});
}
render() {
const {count} = this.state
return (
<div>
<p>Count: {count}</p>
<button onClick={this.increment}>增加计数</button>
</div>
);
}
}
export default Counter;