仅将组中的一个选择添加到阵列

时间:2019-03-05 21:48:25

标签: javascript arrays reactjs object

我正在创建一个足球博彩应用程序,我想在其中选择一场比赛的赢家/输家/平局,然后将其存储在选定的赌注列表中。

enter image description here

到目前为止我有什么

对于每场比赛,您都可以选择团队或平局的获胜者。 # !! Clears the screen, but prints the cmd.exe prompt string once. bash$ echo cls | cmd 方法作为道具向下传递给每个按钮的getSelection处理程序。

然后,onClick方法将按钮click的值添加到数组中,如下所示:

getSelection

我只希望对每个匹配项进行一次选择,就象这样直观地表示:

Codesandbox.

enter image description here

2 个答案:

答案 0 :(得分:1)

此解决方案正在根据用户的选择更新匹配结果。

单个匹配将具有单个结果,即结果将被覆盖

我也使用matchNumber作为索引来跟踪比赛编号。

您的getSelection看起来像这样。

getSelection = (val: object, matchNumber: number) => {
    // 1. Make a shallow copy of the items
    let bets = [...this.state.bets];
    // 2. Make a shallow copy of the item you want to mutate
    let bet = { ...bets[matchNumber] };
    // 3. Replace the property you're intested in
    bet = val;
    // 4. Put it back into our array. N.B. we *are* mutating the array here, but that's why we made a copy first
    bets[matchNumber] = bet;
    // 5. Set the state to our new copy
    this.setState({ bets }, () => console.log(this.state.bets));

更新背景:

<button
    style={{ background: winner == home.name ? "lightblue" : "white" }}
    onClick={() => this.props.getSelection(home, matchNumber)}
  >
    {home.name}
  </button>
  <button
    style={{ background: winner == draw.name ? "lightblue" : "white" }}
    onClick={() => this.props.getSelection(draw, matchNumber)}
  >
    {draw.name}
  </button>
  <button
    style={{ background: winner == away.name ? "lightblue" : "white" }}
    onClick={() => this.props.getSelection(away, matchNumber)}
  >
    {away.name}
  </button>

检查此工作解决方案。 https://codesandbox.io/s/9lpnvx188y

答案 1 :(得分:0)

您是说一次只能添加一次可能性吗? 然后这可能会起作用:

    getSelection = (val: object) => {
      this.setState( {
        bets: [...this.state.bets, val].filter((value, index, self) => { return self.indexOf(value) === index; })
        },
        () => console.log(this.state.bets, "bets")
      );
    };

(也就是说,获取整个数组,添加新值,进行过滤,以便仅获取不同的值,并将其存储在赌注中。)

ala:https://codesandbox.io/s/x2o5m95oxw