react hook 实践中遇到的问题
参考
https://juejin.im/post/5ec7372cf265da76de5cd0c9
主要思想:
每一帧都有独立的状态
每一帧都有独立的Effect
每一帧都有独立的变量
使用ref获取最新值
点击show, 多次点击add, 2s后 输出的值依然是点击show时的值, 而不是最新值, 即使使用对象传递也不会更新, 必须使用ref
import React, { useState, useEffect, useRef } from "react";
const A = ({ count, obj }) => {
const ref = useRef(count);
ref.current = count;
const show = () => {
setTimeout(() => {
console.log("A count", count, obj, ref);
}, 2000);
};
return (
<div>
A count:{count} <button onClick={show}>show</button>
</div>
);
};
export default () => {
const [a, setA] = useState(0);
const [b, setB] = useState({ val: 0 });
const add = () => {
setA(a + 1);
setB({ val: b.val + 1 });
};
const show = () => {
setTimeout(() => {
console.log(a, b);
}, 2000);
};
return (
<div>
a:{a},b:{b.val}
<A count={a} obj={b}></A>
<br></br>
<button onClick={add}>add</button>
<button onClick={show}>show</button>
</div>
);
};
使用ref保存变量的历史记录
但是不知为何却每次都更新了两次….
但是effect中的更新是正确的, 所以尽量使用effect
import React, { useState, useEffect, useRef } from "react";
export default () => {
const [count, setCount] = useState(0);
const ref = useRef([]);
const ref2 = useRef([]);
ref.current.push(count);
useEffect(() => {
ref2.current.push(count);
console.log("ref", ref.current, ref2.current);
});
const add = () => setCount(count + 1);
const del = () => setCount(count - 1);
return (
<div>
count:{count}
<br />
list:{ref.current.join("--")}
<br></br>
<button onClick={add}>add</button>
<button onClick={del}>del</button>
</div>
);
};