如何使用挂钩设置状态?

时间:2019-09-11 02:59:59

标签: javascript reactjs react-redux react-hooks

我有一个这样的对象数组:

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

现在,我有一个按钮,我希望在可见时增加每个水果的数量。因此,每按一次按钮将增加相应水果的计数值并将其存储。

当前,我正在执行

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

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

问题在于这个水果计数功能。可能是什么问题?

1 个答案:

答案 0 :(得分:0)

缺少一些完整的上下文,但这是您提供的代码的一种方法。

它将呈现如下内容:

enter image description here

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>
      ))}
    </>
  );
}