如何在Reactjs中使用clickHandler和useState更新对象数组

时间:2019-07-22 17:30:11

标签: arrays reactjs object updating

如何在Reactjs中使用clickHandler和useState更新对象数组?

import React, { useState } from 'react';

    const TextVote = () => {
      const [votes, setVotes] = useState([
        { text: 'OneOneOne', vote: 0 },
        { text: 'TwoTwoTwo', vote: 5 },
        { text: 'ThreeThreeThree', vote: 0 }
      ]);
      const votesHandler = () => {
        const newClicks = {
          ...votes,
          vote: votes[1].vote + 1
        };
        setVotes(newClicks);
      };

      return (
        <div className='box'>
          <div>{votes[1].text}</div>

          <div>
            <button onClick={votesHandler}>vote</button>
            <div>{votes[1].vote}</div>
          </div>
        </div>
      );
    };

    export default TextVote;

想要知道如何更新阵列以及单击更新后的一些反馈。现在它应该只更新一个对象,但不是。基本思想是对评论投票,并以最高票数返回评论。这是一个模拟,只是为了了解如何工作。我无意渲染整个数组。只是票数最高的那个。

2 个答案:

答案 0 :(得分:0)

票的初始值为数组。但是您将其视为对象。

const newClicks = {
          ...votes,
          vote: votes[1].vote + 1
        };

您应该这样做。

const newClicks = [...votes];
let newVote = { ...newClicks[1] };
newVote.vote++;
newClicks[1] = newVote;
setVotes(newClicks);

享受!

答案 1 :(得分:0)

这种方法呢?每个项目的初始0票阵列处于一种状态,然后随着每次“投票”点击而递增,并存储在该阵列中,每次单击都会对其进行更新。另外,每次显示随机项目时。当然,您可以更改数组的长度(项目数)。

const App = (props) => {
  const [selected, setSelected] = useState(0);
  const [points, setPoints] = useState(new Uint8Array(6));


const votesCount = () => {
  const newClicks = [...points];
  newClicks[selected] +=1;
  setPoints(newClicks);
}


const handleClick = () => {
  const randomNumber = Math.floor(Math.random()*props.itemsToVote.length);
  setSelected(randomNumber);
}

  return (
    <div>
      <p>{props.itemsToVote[selected]}</p>
      <p>Has {points[selected]} votes</p>
      <button onClick={handleClick}>Next</button>
      <button onClick={votesCount}>Vote</button>
    </div>
  )
}

const itemsToVote = ["item1", "item2", "item3", "item4", "item5", "item6", ]