javascript - 如何在 React State 中更新数组的奇异值

标签 javascript reactjs

我正在创建事件处理程序以允许投票,该投票存储在 React 中的数组状态中,但我陷入了困境。

经过一番研究后,我尝试使用另一个数组进行更新,然后将 setState 与新数组一起使用,但这是不正确的

 const App = props => {
 const [selected, setSelected] = useState(0);
 let [votes, setVotes] = useState([1, 2, 3, 4, 5, 6]);
 let newArray = [...votes];
 const handleVote = () => {
  newArray[selected] += 1;
  setVotes([newArray]);
   }; 
 return (
   <div>
     <div>{props.anecdotes[selected]} </div>
     <div>has {votes[selected]} votes</div>

     <div>
       <Button onClick={handleVote()} text="vote" />
       <Button onClick={randomAnecdote} text="next anecdote" />
     </div>
  </div>
   );
   };

预计会增加 votes[0] 的值,其中我使用从状态中选择的 0 来增加 1,但我遇到了无限循环。另外,之前只是将 1 添加到数组末尾

最佳答案

更新投票

handleVote 方法的问题在于,当您调用 setVotes 时,您会这样调用它:setVotes([newArray]),传递 [newArray] 作为参数。因此,在第一遍中,您将 votes 设置为 [[2, 2, 3, 4, 5, 6]],然后在第二遍中,您将得到votes[0],即[2, 2, 3, 4, 5, 6],并添加1,结果如下在字符串连接中,您将得到 ["2,2,3,4,5,61"] 作为 newArray

要解决此问题,请将 setVotes([newArray]) 更改为 setVotes(newArray)

无限循环

您将投票按钮的 onClick 属性设置为等于 handleVote 的输出,而不是等于 handleVote 本身。因此,当您定义投票按钮的 onClick 属性时,您将调用 handleVote 。因此,在每次渲染时,handleVote 都会立即被调用、更新状态并触发重新渲染,从而形成无限循环。

您可以通过更改来解决此问题:

<Button onClick={handleVote()} text="vote" />

至:

<Button onClick={handleVote} text="vote" />

关于javascript - 如何在 React State 中更新数组的奇异值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57749321/

相关文章:

javascript - Vue : delete an item from array when it is passed as a prop to a component?

javascript - 如何创建 Angular Electron 应用程序的 deb 或 exe 文件

reactjs - Firebase 手机登录,在哪里放置 firebase 验证码?

reactjs - 在 github 页面上部署 Reactjs 网站并使用路由会导致刷新时出现 404 错误

javascript - 如何更改由 JavaScript 函数生成的 docx 中的字体

javascript - 查找所选元素的索引

javascript - 在 Javascript 中使用单引号和双引号转义和取消转义字符串

javascript - 在搜索结果页面显示过滤结果

reactjs - 开 Jest : How to test function that calls bind(this)

javascript - 在功能组件初始渲染时将变量添加到存储中