反应挂钩useState isAction未定义

时间:2019-12-12 06:35:59

标签: reactjs react-hooks

单击“单击”时,未定义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;

full code

4 个答案:

答案 0 :(得分:4)

useState返回一个包含2个项目的数组。您正在尝试对象分解,但是必须为array destructuring

const [isAction, setIsAction] = useState(false);

答案 1 :(得分:1)

更改此:

const {isAction, setIsAction} = useState(false);

收件人

 const [isAction, setIsAction] = useState(false);

答案 2 :(得分:0)

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;

答案 3 :(得分:0)

您正在构造具有2个项目的useState返回数组。更改此:

const {isAction, setIsAction} = useState(false);

const [isAction, setIsAction] = useState(false);

Ex:

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