一个react的hooks的问题
useEffect(() => {
console.log(666)
}, [a,b]}
a和b同时改变的话,666会打印两次,
这种情况怎么避免呢
回答
摘抄自另一个问题的回答:https://segmentfault.com/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;