繁体   English   中英

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

[英]How can I fix my code to display correct index of array

我有一个事件处理程序,它计算投票最多的词组,并在每次投票完成时将其打印出来。 但是,在我进行第一次投票之后,我的代码总是给出数组的最后一个短语,而不是投票最多的短语。 第一次投票后完美运行。 我在代码中做错了什么?

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有一些了解。 状态更改时,将使用新值重新渲染组件。

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

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


您应该替换此行let array = new Array(...votes); 这样let array = new Array(...newArray); 可变votes保持先前状态。 当使用它时,条件if (votes[a] === i)对于所有对象都将评估为true ,因为它们在开始时均为0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM