将 Hook 调用语句放置在代码的顶层,避免被包在条件语句中。
示例代码:
function MyComponent(props) {
const [count, setCount] = useState(0);
// 错误的写法:在条件语句中调用了 Hook
if (props.condition) {
const [name, setName] = useState('John');
}
return (
You clicked { count } times.
);
}
修改后的代码:
function MyComponent(props) {
const [count, setCount] = useState(0);
const [name, setName] = useState('John');
// 正确的写法:将 Hook 放置在顶层
if (props.condition) {
// 修改 state 值
setName('Lucy');
}
return (
You clicked { count } times.
Hello, { name }
);
}