【问题标题】:How to set state using Hooks?如何使用 Hooks 设置状态?
【发布时间】:2019-09-11 02:59:59
【问题描述】:

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

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

我猜是这个 fruitsCount 函数的问题。可能是什么问题?

【问题讨论】:

  • 你能分享完整的代码吗? selected 是什么?
  • 你说 fruitsArray 但你在 setCount 中设置一个对象?
  • 它实际上是一个对象数组。
  • @skovy setSelected(Math.floor(Math.random() * 3));通过选择,我在另一个按钮单击时随机显示水果名称。

标签: javascript reactjs react-redux react-hooks


【解决方案1】:

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

它将呈现如下内容:

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

【讨论】:

  • 实际上在render方法中,我没有使用map,所以无法将index的引用传递给updateCount函数
  • return ( &lt;div&gt; &lt;div&gt;{fruitArray[selected].fruit}&lt;/div&gt; &lt;div&gt;has {fruitArray[selected].count} votes&lt;/div&gt; &lt;br/&gt; &lt;button onClick={fruitCount}&gt;Count&lt;/button&gt; &lt;button onClick={nextFruit}&gt;Next fruit&lt;/button&gt; &lt;/div&gt; )
  • 如果您使用的是 setSelected(Math.floor(Math.random() * 3)); 。就像你上面说的,使用那个的返回值?
  • 这是我用来随机显示引号的单独函数
  • const nextFruit = () => { setSelected(Math.floor(Math.random() * 3)); }
猜你喜欢
  • 2019-11-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-02
  • 1970-01-01
  • 2019-09-07
  • 2020-01-15
  • 2021-02-28
  • 1970-01-01
相关资源
最近更新 更多