简体   繁体   English

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

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

I have an event handler which calculates the most voted phrase and prints it every time voting is done. 我有一个事件处理程序,它计算投票最多的词组,并在每次投票完成时将其打印出来。 However, after my first vote, my code always gives the last phrase of the array instead of the most voted one. 但是,在我进行第一次投票之后,我的代码总是给出数组的最后一个短语,而不是投票最多的短语。 It works after the first vote perfectly. 第一次投票后完美运行。 What have I done wrong in my code? 我在代码中做错了什么?

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

There is something you should know about useState . 您应该对useState有一些了解。 When the state changes, the component is re-rendered with the new values. 状态更改时,将使用新值重新渲染组件。

What is happening here is that votes did not change after setVotes , because you're still executing the old state. 这里发生的事情是setVotes之后votes没有改变,因为您仍在执行旧状态。

setVotes(newArray);
let array = new Array(...votes); // votes did not change here

For this reason, you should avoid using state variables when you don't need them. 因此,在不需要状态变量时,应避免使用它们。

One solution (maybe not the best, but will help you better understand states) would be: 一种解决方案(可能不是最好的解决方案,但是可以帮助您更好地了解状态)是:

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


You should replace this line let array = new Array(...votes); 您应该替换此行let array = new Array(...votes); with this let array = new Array(...newArray); 这样let array = new Array(...newArray); . The variable votes holds the previous state. 可变votes保持先前状态。 When you use it the condition if (votes[a] === i) will evaluate to true for all objects, as they all 0 at the beginning. 当使用它时,条件if (votes[a] === i)对于所有对象都将评估为true ,因为它们在开始时均为0

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

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