【问题标题】:Add 1 with the click of a button in React在 React 中单击按钮添加 1
【发布时间】:2021-05-09 22:49:52
【问题描述】:

现在是我应用开发下一阶段的时候了:

function App() {
  const [number, setNumber] = useState('');
  const [totPoints, setTotPoints] = useState('');
  const [players, setPlayers] = useState(getLocalStorage());

const onOnePointMade = (e) => {
    e.preventDefault();
    const existingScorer = players.find((player) => player.nummer === number);

    if (existingScorer) {
      setTotPoints(+totPoints + 1);
      const newPlayer = {
        totPoints: totPoints,
      };
      setPlayers([...players, newPlayer]);
      console.log(totPoints);
    } else {
      setTotPoints(+totPoints + 1);
      const newPlayer = {
        id: nanoid(4),
        nummer: number,
        totPoints: totPoints,
      };
      setPlayers([...players, newPlayer]);
    }
    setNumber('');
  };

上面的代码,我要纯英文的:

  1. 检查玩家(=number)是否在列表中players
  2. 如果是:将他目前的得分加 1 (+1) (totPoints)
  3. 如果否:将数字和一个点添加到列表中(totPoints = 1)

也感谢您对这个问题的帮助

提前致谢

附言 我尝试使用从@Robin 获得的代码

const onOnePointMade = (e) => {
    e.preventDefault();
    const scorer = [...players];
    const existingScorer = scorer.find((player) => player.number === number);
    const new_totpoints = totPoints + 1;

    if (existingScorer) {
      setTotPoints(new_totpoints);
      existingScorer.totPoints = new_totpoints;
      setPlayers(scorer);
    } else {
      const newScorer = {
        id: nanoid(4),
        number: number,
        totPoints: new_totpoints,
      };
      setPlayers([...players, newScorer]);
    }
  };

不幸的是,它并没有像我预期的那样工作: 我第一次添加玩家编号 3 时它是正确的,即 1 分 如果 3 号玩家得分更多,则正确添加。 但! 假设他得了 3 分,如果我现在加上 4 号球员,列出的是他得了 4 分,而不是 1 分 希望大家理解,附上链接: https://github.com/peter-swe/tot-points

【问题讨论】:

  • 我认为您需要更具体地解决您的问题。您当前的代码有什么问题?

标签: reactjs react-hooks


【解决方案1】:

在现有播放器块的代码中,您尝试添加新播放器。 通过查看您的解释,它应该找到播放器并更新他们的totpoints

我们不能直接更新 state 的属性所以取一个 state 的副本,然后更新新副本中的 totpoint,并将新副本设置为 state。

    const _players = [...players];
    const existingScorer = _players.find((player) => player.nummer === number);
    const new_totpoints = totPoints + 1
    if (existingScorer) {
      setTotPoints(new_totpoints);
      existingScorer.totPoints = new_totpoints
      setPlayers(_players);
     }

【讨论】:

  • 感谢罗宾的回答。我一搬家就会检查这个,告诉你进展如何
  • 对不起,你的代码不起作用:如果我举个例子:我有球员号码 1、3、5、7 在名单上,球员号码 7 torPoints = 9。下次球员号码 3 score 下一次玩家 3 号得分时 totPoints = 10,即添加到 7 号 torPoints +1 (9 + 1) 等。
  • 为了你自己看,我附上github仓库[github.com/peter-swe/scored-point]
猜你喜欢
  • 2022-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-26
  • 2018-05-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多