简体   繁体   English

如何使用挂钩设置状态?

[英]How to set state using Hooks?

I have an array of objects like this : 我有一个这样的对象数组:

var fruitsArray = [{ fruit: 'Apple', count: 0 },{fruit: 'Banana', count: 0 },{fruit: 'Grapes', count: 0}]

Now I have a button where I want to increase the count of every fruit whenever it's visible. 现在,我有一个按钮,我希望在可见时增加每个水果的数量。 So, every button press will increase the count value of respective fruits and store it. 因此,每按一次按钮将增加相应水果的计数值并将其存储。

Currently, I am doing : 目前,我正在做:

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

 const fruitsCount = () => {
      console.log(fruitsArray[selected].count += 1)
      setCount({
        ...fruitsArray,
        count : fruitsArray[selected].count + 1
      })
    }

Issue is with this fruitsCount function I guess. 我猜这是这个FruitsCount函数的问题。 What may be the problem? 可能是什么问题?

There is some full context missing, but here is one approach for the code you provided. 缺少一些完整的上下文,但这是您提供的代码的一种方法。

It will render something like this: 它将呈现如下内容:

在此处输入图片说明

var fruitsArray = [
  { fruit: "Apple", count: 0 },
  { fruit: "Banana", count: 0 },
  { fruit: "Grapes", count: 0 }
];

function App() {
  const [fruits, setCount] = React.useState(fruitsArray);

  const updateCount = index => {
    setCount(
      fruits.map((fruit, i) => {
        if (index === i) {
          // Create a new object to avoid mutating anything in state
          return {
            ...fruit,
            count: fruit.count + 1
          };
        } else {
          // Reuse the existing fruit object since it didn't change
          return fruit;
        }
      })
    );
  };

  return (
    <>
      {fruits.map((fruit, index) => (
        <button key={fruit.fruit} onClick={() => updateCount(index)}>
          {fruit.fruit}: {fruit.count}
        </button>
      ))}
    </>
  );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM