在使用useState时,需要注意以下几点:
示例代码: 避免在useState中使用可变变量或函数:
// 错误示例 const [count, setCount] = useState(0); const multiplier = 2;
function handleClick() { setCount(count * multiplier); }
// 正确示例 const [count, setCount] = useState(0);
function handleClick() { setCount(count => count * 2); }
避免在函数式组件渲染中有副作用:
// 错误示例 const [count, setCount] = useState(0);
useEffect(() => {
document.title = You clicked ${count} times
;
setCount(count + 1);
});
// 正确示例 const [count, setCount] = useState(0);
useEffect(() => {
document.title = You clicked ${count} times
;
}, [count]);
使用函数形式的异步更新状态:
// 错误示例 const [count, setCount] = useState(0);
function handleClick() { setTimeout(() => { setCount(count + 1); }, 1000); }
// 正确示例 const [count, setCount] = useState(0);
function handleClick
上一篇:避免在React中出现渲染警告