【问题标题】:How to use callback of setState()? [duplicate]如何使用 setState() 的回调? [复制]
【发布时间】:2021-09-28 12:27:37
【问题描述】:

我正在尝试使用 setState() 的回调来检查状态是否正确更改。但是,我收到错误 Expected 1 arguments, but got 2

   setCurrentLength(300, () => {
      console.log('Current length ', currentLength);
   });

如何解决? 谢谢

【问题讨论】:

  • setState 作为来自 useState 钩子的元组的第二部分返回没有此功能。您尝试使用的回调函数是类 Component 中 this.setState 的一部分。

标签: javascript reactjs typescript state


【解决方案1】:

您正在使用setState 的回调。但是你使用的是useState钩子。

使用应该使用 useEffect 和依赖数组,所以当 currentLength 被更改时,你的 console.log 将被执行。

useEffect(()=>{
  console.log('Current length ', currentLength);
}, [currentLength]);

【讨论】:

    猜你喜欢
    • 2020-09-25
    • 1970-01-01
    • 2017-06-21
    • 2019-09-18
    • 2021-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-12
    相关资源
    最近更新 更多