rt:这两者在选择数据合并处理上会有什么异同嘛?
比如说我多次调用setState和useState数组结构出的dispatcher处理状态变更
在变更合并等处理上会有什么区别吗?
以下代码会输出:0000
const Example = () => {
const [state, stateDispatcher] = useState(0);
useEffect(() => {
stateDispatcher(state + 1);
console.log(state);
stateDispatcher(state + 1);
console.log(state);
setTimeout(() => {
stateDispatcher(state + 1);
console.log(state);
stateDispatcher(state + 1);
console.log(state);
}, 100);
}, []);
return null;
};
export default Example;
以下为:0011...
const Example = () => {
const [state, stateDispatcher] = useState(0);
stateDispatcher(state + 1);
console.log(state);
stateDispatcher(state + 1);
console.log(state);
setTimeout(() => {
stateDispatcher(state + 1);
console.log(state);
stateDispatcher(state + 1);
console.log(state);
}, 100);
return null;
};
export default Example;
以下代码输出0023
class Example extends React.Component {
constructor() {
super();
this.state = {
val: 0,
};
}
componentDidMount() {
this.setState({ val: this.state.val + 1 });
console.log(this.state.val);
this.setState({ val: this.state.val + 1 });
console.log(this.state.val);
setTimeout(() => {
this.setState({ val: this.state.val + 1 });
console.log(this.state.val);
this.setState({ val: this.state.val + 1 });
console.log(this.state.val);
}, 100);
}
render() {
return null;
}
}
export default Example;
useState
和setState
的状态变更没区别;纯属写法不同导致的。
首先要先理解几个概念:
如果需要科普可以看看这个文章解密React state hook。
好像已经不需要解释了。
demo2是个死循环,稍稍修改下代码:
修改demo3写法,使其和demo1输出一致: