

给变量用setZhi这个方法操作后控制台没变,但是视图倒刷新了,这是什么原理?


视图 刷新了说明 生效了 ,至于 赋值后直接打印 没立即变,是因为 setState是异步的,不能直接看到结果 。
因为 setZhi 需要改变 视图, 是副作用 操作 想要看到 用
useEffect(() => {
console.log(zhi);
}, [name])
或者 useRef 实现
function Counter() {
const [count, setCount] = useState(0);
const prevCountRef = useRef();
useEffect(() => {
prevCountRef.current = count;
});
const prevCount = prevCountRef.current;
return <h1>Now: {count}, before: {prevCount}</h1>;
}
https://zh-hans.reactjs.org/docs/hooks-faq.html#how-to-get-the-previous-props-or-state