如何在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;想知道如何在单击更新后更新数组和一些反馈。现在,它应该只更新一个对象,但它不是,基本思想是投票支持评论,并以最多的票数返回评论。这是一个模仿秀,只是为了了解它的工作原理。我不打算渲染整个数组。只有得票最多的那个。
发布于 2019-07-22 19:11:44
选票的初始值是数组。但你把它当成了对象。
const newClicks = {
...votes,
vote: votes[1].vote + 1
};你应该这样做。
const newClicks = [...votes];
let newVote = { ...newClicks[1] };
newVote.vote++;
newClicks[1] = newVote;
setVotes(newClicks);享受吧!
发布于 2020-06-13 17:51:34
这个方法呢?每个项目的初始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", ]https://stackoverflow.com/questions/57151020
复制相似问题