You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中如何通过按钮递增数组对应选中项的投票数值?

问题解决:React中点击按钮更新对应轶事投票数

核心错误分析

你的代码存在三个关键问题导致投票功能失效:

  • 状态更新方式错误:voteClick中直接修改原状态对象属性,且将单个数值传给setVotes,违反了React状态不可变的原则,无法触发状态更新。
  • 显示非实时状态:渲染时使用的copy是组件初始化时的普通对象,不是React状态,投票数更新后不会同步显示。
  • 初始投票值设置错误:初始投票值设为0-6是笔误,正常应该所有轶事初始票数为0。

修正后的完整代码

import { useState } from 'react'

const App = () => {
  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 10 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.',
    'Programming without an extremely heavy use of console.log is same as if a doctor would refuse to use x-rays or blood tests when diagnosing patients.', 
  ]

  const [selected, setSelected] = useState(0)
  // 根据轶事数量自动生成全0的初始投票状态
  const [votes, setVotes] = useState(() => 
    anecdotes.reduce((acc, _, index) => {
      acc[index] = 0
      return acc
    }, {})
  )

  const voteClick = () => {
    // 函数式更新确保拿到最新状态,创建新对象避免修改原状态
    setVotes(prevVotes => ({
      ...prevVotes,
      [selected]: prevVotes[selected] + 1
    }))
  }

  const randAnecdote = () => {
    const len = anecdotes.length;
    setSelected(Math.floor(Math.random() * len));
  };
 
  return (
    <div>
      <div>{anecdotes[selected]}</div><br />
      This anecdote has {votes[selected]} votes<br />
      <button onClick={voteClick}>Vote</button>
      <button onClick={randAnecdote}>Next Anecdote</button>
    </div>
  )
}

export default App

关键修改说明

  • 投票状态初始化:用reduce动态生成初始投票对象,新增轶事时无需手动修改初始值,更灵活。
  • 正确的状态更新:使用函数式更新获取最新状态,通过展开运算符创建新对象,只修改选中项的票数,符合React不可变状态规则,能正确触发页面重渲染。
  • 实时显示投票数:渲染时直接引用votes[selected],状态更新后页面会自动同步显示最新票数。

内容的提问来源于stack exchange,提问作者pippuriaika

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 18:25:40