【问题标题】:React: How to call react hooks inside the event handler?React:如何在事件处理程序中调用反应钩子?
【发布时间】:2020-02-17 04:28:03
【问题描述】:

我在反应功能组件中有以下代码。当我单击按钮并运行处理程序时,会发生错误: Invalid hook call. Hooks can only be called inside of the body of a function component.

const handleClick = () => {
  const [count, setCount] = useState(x); // this is wrong
};

我试图搜索修复,有人建议:

const [count, setCount] = useState(0);

const handleClick = () => {
  setCount(x); // setCount is ok, but I cannot set other dynamic states
};

但是,我的count 状态是动态的,我无法从头开始全部初始化。当我使用类组件时,这很容易。

// old syntax from class components
state = {
  count: 0
};

const handleClick = () => {
  this.setState({
    other_count: x
  })
};

功能组件如何达到同样的效果?

【问题讨论】:

  • 你能发布你的 package.json 吗?
  • 你能发布你的整个组件吗
  • “react”:“^16.9.0”,“react-dom”:“^16.9.0”,“react-redux”:“^7.1.1”,“react-router- dom": "^5.0.1", "react-scripts": "2.1.8"
  • other_count 是计算密钥吗?

标签: javascript reactjs react-hooks


【解决方案1】:

如果您想动态使用state,请将object 用作state。

牢记不变性。

const [state, setState] = useState({ count: 0 });

const handleClick = () => {
  setState({...state, other_count: x });
}

【讨论】:

    【解决方案2】:

    您可以使用多个状态或单个状态的对象。

    第一种方式:

    const [count, setCount] = useState(0);
    const [otherCount, setOtherCount] = useState(0);
    
    const handleClick = () => {
      // count is already available to you.. so update the other state
      setOtherCount(x);
    };
    

    第二种方式:

    const [compState, setCompState] = useState({ count: 0, other_count: 0 });
    
    const handleClick = () => {
      setCompState(prevState => { ...prevState, other_count: x });
    };
    

    DEMO 为第二种方式。

    【讨论】:

    • 如果我从不同的函数更新多个状态会失败吗?例如来自不同异步函数的state = { a: 1, b: 2 } 和setState({ ...state, a: 10 }) setState({ ...state, b: 20 }),是否存在竞争条件?
    • 如果你在异步函数中更新,那么你可以使用另一种方式来更新状态。 setState(prevState => { ...prevState, a:10 })
    • @5413668060 您也可以查看此链接。我使用 setTimeout 来测试异步行为。 codesandbox.io/s/upbeat-bird-l97e4?fontsize=14
    猜你喜欢
    • 2021-12-01
    • 2021-04-07
    • 2019-08-11
    • 2023-03-24
    • 2019-06-01
    • 2021-06-27
    • 1970-01-01
    • 2019-07-26
    • 1970-01-01
    相关资源
    最近更新 更多