我有一个事件处理程序,它计算投票最多的词组,并在每次投票完成时将其打印出来。但是,在我进行第一次投票之后,我的代码总是给出数组的最后一个短语,而不是投票最多的短语。第一次投票后完美运行。我在代码中做错了什么?
const App = props => {
const [selected, setSelected] = useState(0);
let [votes, setVotes] = useState([0, 0, 0, 0, 0, 0]);
let [mostVotes, setMostVotes] = useState(0);
const handleVote = () => {
let newArray = [...votes];
newArray[selected] += 1;
setVotes(newArray);
let array = new Array(...votes);
let i = Math.max(...array);
for (var a = 0; a < array.length; a++) {
if (votes[a] === i) setMostVotes(a);
}
};
return (
<div>
<h2>Anecdote of the day</h2>
<div>{props.anecdotes[selected]} </div>
<div>has {votes[selected]} votes</div>
<div>
<Button onClick={handleVote} text="vote" />
<Button onClick={randomAnecdote} text="next anecdote" />
</div>
{console.log(mostVotes)}
<h2>Anecdote with the most votes</h2>
<p>{anecdotes[mostVotes]}</p>
</div>
);
};
const anecdotes = [
"If it hurts, do it more often",
"Adding manpower to a late software project makes it later!",
"The first 90 percent of the code accounts for the first 90 percent of
the development time...The remaining 10 percent of the code accounts
for the other 90 percent of the development time.",
"Any fool can write code that a computer can understand. Good
programmers write code that humans can understand.",
"Premature optimization is the root of all evil.",
"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are, by
definition, not smart enough to debug it."
];
答案 0 :(得分:2)
关于useState
,您应该了解一些知识。状态更改时,将使用新值重新渲染组件。
这里发生的是votes
在setVotes
之后没有改变,因为您仍在执行旧状态。
setVotes(newArray);
let array = new Array(...votes); // votes did not change here
由于这个原因,当不需要状态变量时,应该避免使用它们。
一种解决方案(也许不是最好的解决方案,但可以帮助您更好地了解状态):
let [votes, setVotes] = useState([0, 0, 0, 0, 0, 0]);
let mostVotes = 0;
//This is executed every time the component is re-rendered
let array = new Array(...votes);
let i = Math.max(...array);
for (var a = 0; a < array.length; a++) {
if (votes[a] === i) {mostVotes = a};
}
const handleVote = () => {
let newArray = [...votes];
newArray[selected] += 1;
setVotes(newArray); //This triggers a re-render
};
答案 1 :(得分:0)
您应该替换此行
let array = new Array(...votes);
有了这个
let array = new Array(...newArray);
。
变量votes
保留先前的状态。使用它时,条件if (votes[a] === i)
将对所有对象求值为true
,因为它们一开始都是0
。