目录
setState()方法的两个作用:
1 修改state
2 更新组件

推荐原因
解决该问题: 后面的setState()不能依赖于前面的setState()
看下面的案例
- import React from "react";
- import ReactDOM from "react-dom";
-
- class App extends React.Component {
- state={
- count:1
- }
- fn=()=>{
- this.setState({
- count:this.state.count+1
- })
- console.log("count的值:"+this.state.count)
- this.setState({
- count:this.state.count+1
- })
-
- }
- render() {
- console.log("render")
- return (
- <div>
- <p>count:{this.state.count}p>
- <button onClick={this.fn}>点我button>
- div>)
- }
- }
-
-
- ReactDOM.render(<App/>, document.getElementById("root"));
效果
点击按钮,count的值从1加到2,但是,明明有两次setState(),每次都给count加1了

用推荐语法就可以解决这个问题
- import React from "react";
- import ReactDOM from "react-dom";
-
- class App extends React.Component {
- state={
- count:1
- }
- fn=()=>{
-
- this.setState((state,props)=>{
- return{
- count:state.count+1
- }
- })
- console.log("count的值:"+this.state.count)
- this.setState((state,props)=>{
- return{
- count:state.count+1
- }
- })
- }
- render() {
- console.log("render")
- return (
- <div>
- <p>count:{this.state.count}p>
- <button onClick={this.fn}>点我button>
- div>)
- }
- }
-
-
- ReactDOM.render(<App/>, document.getElementById("root"));
效果
点击按钮,count的值从1变成3,后面的setState()可以依赖于前面的setState()

注意点
1 setState()更新数据是异步更新的

2 可以多次调用setState(),但是最终只会触发一次重新渲染render (因为考虑到性能,会把多次的setState结果合并)

场景: 在状态更新(页面完成重新渲染)后立即执行某个操作
- fn=()=>{
-
- this.setState((state,props)=>{
- return{
- count:state.count+1
- }
- },()=>{
- console.log("更新后的:"+this.state.count)
- })
-
- }
