useState与this.setState
- this.setState中setTimeout能获取到新的state
- this.setState同一时间段的会合并
- react能控制的周期和合成事件等方法中是异步的,即执行完不会立即更新组件实例的state
- 原生事件和setTimeout中state是同步更新的
import React from 'react';
class Page extends React.PureComponent {
constructor(props) {
super(props);
this.state = {}
}
componentDidMount() {
this.setState({
a:1
})
this.setState({
b:2
})
this.setState({
c:3
})
this.setState({
c: this.state.c + 1
})
setTimeout(() => {
this.setState({
d:1
})
console.log(this.state.d)
this.setState({
d: this.state.d + 2
})
console.log(this.state.d)
this.setState({
d: this.state.d + 3
})
console.log(this.state.a, this.state.b,this.state.c,this.state.d)
})
}
render() {
return (
<div>
<div>a:{this.state.a}</div>
<div>b:{this.state.b}</div>
<div>c:{this.state.c}</div>
</div>
);
}
}
export default Page;
视图结果:
console结果:
-useState的setXX的方法也会合并,且setTimeout/原生事件中合并
- setTimeout和原生事件中不能获取到最新的state
- 下面useState封装的setState,多个setState对不通的key也会相互覆盖
import { useEffect, useState } from "react";
export default function Page() {
const [state, setState_] = useState({});
const setState = (newState) => {
setState_({
...state,
...newState
})
}
const [A, setA] = useState();
const [B, setB] = useState();
const [C, setC] = useState();
useEffect(() => {
setState({
a: 1
})
setState({
b: 2
})
setState({
c: 3
})
setA(11); setB(22); setC(33);
setTimeout(() => {
setState({
c: 3
})
console.log(state, A, B, C)
})
}, [])
return (
<>
<div>a:{state.a}</div>
<div>b:{state.b}</div>
<div>c:{state.c}</div>
<hr />
<div>A:{A}</div>
<div>B:{B}</div>
<div>C:{C}</div>
</>
)
}
视图结果:
console结果: