【问题标题】:[react]: useMemo returns first element when passed an array[react]:useMemo 在传递数组时返回第一个元素
【发布时间】:2021-04-23 12:03:03
【问题描述】:

这是示例代码

export default function App() {
  const [links] = React.useMemo(
    () => ['hello', 'world'],[]
  )
  return (
    <div className="App">
      <button onClick={() => console.log(links)}>console</button>
    </div>
  );
}

当按钮被点击时,我在控制台中得到关注

hello

我的问题:由于它返回第一个元素,我无法映射到 links 数组。它甚至是我应该使用useMemo 的方式吗?请注意,我传递的数组是例如,元素可能会比简单的字符串更大。

【问题讨论】:

  • () =&gt; [['hello', 'world'],],[],在您的代码中,links = 'hello'
  • 你为什么用React.useMemo()来初始化你的链接,就用useState
  • 试试const links = React.useMemo(() =&gt; ['hello', 'world'],[]);,因为如果你解构返回的数组来获取它的第一个值,你会得到第一个值,即hello

标签: javascript arrays reactjs state react-usememo


【解决方案1】:

正如@Andrea Giammarchi 所指出的,问题是左值中链接的解构

以下代码修复了问题:

- const [links] = React.useMemo(
+ const links = React.useMemo(

【讨论】:

    猜你喜欢
    • 2019-07-22
    • 2016-10-31
    • 2011-07-12
    • 2020-11-24
    • 2014-07-28
    • 2018-06-20
    • 1970-01-01
    • 2018-10-01
    • 2012-04-10
    相关资源
    最近更新 更多