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

标签 javascript reactjs

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

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/

相关文章:

css - 使用 NavBar 组件时 id 和 class 的区别?

node.js - React.js 从本地文件读取

reactjs - 为什么在handleLogin方法中this.props未定义?

javascript - 从用户那里获取输入并查询数据库

javascript - 带有 WordPress 插件的 Webpack,最好的方法是什么?

javascript - 映射从 React 中的 Express 服务器获取的 JavaScript 对象

javascript - 在不使用 react-native-web 的情况下为 ReactJS 创建 "TouchableOpacity"

javascript - 为什么appendChild不能在<li>模板标签上工作

javascript - 在日历函数中使用 Promise 响应(需要来自 ajax 调用的数据)

Javascript:使用鼠标悬停/鼠标悬停启用/禁用按钮