您可以在条件中使用 useState 中的 'setter' 吗?
Can you use the 'setter' from useState inside a condition?
我知道一般原则是 avoid using hooks inside a loop, condition, or nested function 但是关于设置状态,这样可以吗?
function myComponent() {
const [myVar, setMyVar] = useState();
...
const nestedFunction = () => {
if (condition) {
setMyVar(value);
}
}
}
如果没有,我如何使用 Hooks 完成此操作?
是的,完全没问题。 setter 不是钩子。 useState
是您示例中唯一的 "hook"。
我知道一般原则是 avoid using hooks inside a loop, condition, or nested function 但是关于设置状态,这样可以吗?
function myComponent() {
const [myVar, setMyVar] = useState();
...
const nestedFunction = () => {
if (condition) {
setMyVar(value);
}
}
}
如果没有,我如何使用 Hooks 完成此操作?
是的,完全没问题。 setter 不是钩子。 useState
是您示例中唯一的 "hook"。