摘抄自另一个问题的回答:https://ostack.cn/q/10...
import React, { useState, useEffect, useRef } from 'react';
const One = _ => {
const [a, setA] = useState(0);
const [b, setB] = useState(0);
const ref = useRef({ a, b });
useEffect(() => {
let { a: prevA, b: prevB } = ref.current;
console.log('更新前:', prevA, prevB);
console.log('更新后:', a, b);
//a 和 b 同时改变的时候不执行
if (prevA !== a && prevB !== b) {
return
}
console.log(666);
ref.current = { a, b };
}, [a, b]);
return (
<>
<h1>{a + b}</h1>
<button onClick={_ => setA(d => d + 1)}>Chang A</button>
<button onClick={_ => setB(d => d + 1)}>Chang B</button>
</>
);
};
export default One;
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…