gpt4 book ai didi

javascript - 如何修复我的代码以显示正确的数组索引

转载 作者:行者123 更新时间:2023-12-01 00:40:30 25 4
gpt4 key购买 nike

我有一个事件处理程序,它计算投票最多的短语并在每次投票完成时打印它。然而,在我第一次投票之后,我的代码总是给出数组的最后一个短语,而不是投票最多的短语。第一次投票后效果很好。我的代码做错了什么?

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."
];

最佳答案

关于useState,您应该了解一些事情。当状态更改时,组件将使用新值重新呈现。

这里发生的情况是,votessetVotes 之后没有改变,因为您仍在执行旧状态。

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


关于javascript - 如何修复我的代码以显示正确的数组索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57756923/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com