【问题标题】:React: useState hook updates only the last instance from multiple instances of the same functional componentReact:useState 挂钩仅更新来自同一功能组件的多个实例的最后一个实例
【发布时间】:2021-06-22 21:58:04
【问题描述】:

当我单击 3 个项目中的任何一个时,只会增加最后一个项目。当对 Item 组件使用基于类的组件而不是功能组件时,一切都很好。有人可以解释一下吗?

const { Fragment, useState } = React;

const List = () => {
  return (
    <Fragment>
      <Item /><Item /><Item />
    </Fragment>
  )
};

const Item = () => {
  [count, setCount] = useState(0);
  return (
    <div className="item" onClick={() => setCount(count + 1)}>{count}</div>
  );
};

ReactDOM.render(
  <List />,
  document.getElementById('root')
);

https://jsfiddle.net/antonfil/qk08srn5/17/

【问题讨论】:

    标签: reactjs react-hooks


    【解决方案1】:

    当你这样做时,你正在创建全局变量

    [count, setCount] = useState(0);
    

    你需要做的

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

    【讨论】:

    • 谢谢。真的是一个非常简单的错误,也是一个很好的例子,为什么在一些 Studio 中而不是在 JSfiddle 中编写代码更好。如果你不小心声明了一个全局变量,ESLint 会警告你。
    猜你喜欢
    • 2012-03-09
    • 2011-04-29
    • 2018-11-21
    • 1970-01-01
    • 2016-08-22
    • 2018-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多