簡體   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