单击"单击"时,setIsAction 未定义。我一定错过了一些显而易见的东西。知道吗?
import React, {useEffect, useState} from 'react';
function App() {
const {isAction, setIsAction} = useState(false);
useEffect(() => {
if (isAction) {
console.log('use effect');
}
}, [isAction, setIsAction]);
return (
<div
onClick={() => {
setIsAction(true);
}}
>
click
</div>
);
}
export default App;
完整代码
useState 返回一个包含 2 个项目的数组。您正在尝试对象解构,但它必须是数组解构。
const [isAction, setIsAction] = useState(false);
更改以下内容:
const {isAction, setIsAction} = useState(false);
自
const [isAction, setIsAction] = useState(false);
import React, {useEffect, useState} from 'react';
function App() {
# need to change here just
const [isAction, setIsAction] = useState(false);
useEffect(() => {
if (isAction) {
console.log('use effect');
}
}, [isAction, setIsAction]);
return (
<div
onClick={() => {
setIsAction(true);
}}
>
click
</div>
);
}
export default App;
您正在解构而不是使用带有 2 个项目的状态返回数组。更改此内容:
const {isAction, setIsAction} = useState(false);
自
const [isAction, setIsAction] = useState(false);
前任:
import React, {useEffect, useState} from 'react';
function App() {
const [isAction, setIsAction] = useState(false);
useEffect(() => {
if (isAction) {
console.log('use effect');
}
}, [isAction, setIsAction]);
return (
<div
onClick={() => {
setIsAction(true);
}}
>
click
</div>
);
}
export default App;
我已经修改了您的示例以获得更好的上下文.您可以在此处找到演示:https://stackblitz.com/edit/react-stfhm5