javascript 如何在React中存储累加值(整数)?

p8h8hvxi  于 2023-02-11  发布在  Java
关注(0)|答案(2)|浏览(125)

我有一个轶事数组和两个按钮。一个是投票,另一个是随机选择下一个轶事。当我点击投票按钮时,投票被视为增加的数字。然而,问题是,当我点击下一个轶事时,投票保持不变,而不是在新的轶事出现时重置为数字0。
我尝试存储投票数,首先向数组enectes,enectes.forEach(function(enectode){enectode.vote =“”})添加一个新属性Vote,该属性的值为空““;然后将增加的投票数推送到数组的一个新副本中,但是没有成功,我该怎么做呢?
App.js

import { useState } from 'react'

const inlineParagraph = {
  display: 'inline-flex',
  flexDirection: 'column',
}

const inlineButton = {
  display: 'flex',
  marginTop: '5px',
  gap: '10px',
}

const Button = (props) => {
  return (
    <div>
      <button onClick={props.handleClick}> {props.text} </button>
    </div>
  )
}

const App = () => {

  const handleClick2 = () => {
    setSelected(Math.floor(Math.random()*anecdotes.length))
  }

  const handleVote = () => {
    setVote(vote + 1) 
  }

  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.',
    'The only way to go fast, is to go well.'
  ]
   
  const [selected, setSelected] = useState(0)
  const [vote, setVote] = useState(0)

  const copyAnecdotes = [...anecdotes]

  return (
    <div style={inlineParagraph}>
      { anecdotes[selected] }

      <div style={inlineButton} >
        <Button handleClick={handleClick2} text="next anecdotes" setSelected={setSelected} />
        <Button handleClick={handleVote} text="vote" setSelected={setSelected} /> {vote}
      </div>
    </div>
  )
}

export default App
m4pnthwp

m4pnthwp1#

应在handleClick2函数中重置投票

const handleClick2 = () => {
    setSelected(Math.floor(Math.random()*anecdotes.length));
    setVote(0); 
}
8wtpewkr

8wtpewkr2#

首先,您需要一个投票数组:

const [votes, setVotes] = useState(() => Array(anecdotes.length).fill(0));

然后一个函数添加选票:

const handleVotes = () => {
  setVote((votes) =>
    votes.map((vote, index) => (index === selected ? vote + 1 : vote))
  );
};

并显示正确的投票:

{votes[selected]}

相关问题