如果单击了某个项目(并且之前已经将其添加到数组中),如何从数组中删除该项目?

How to remove an item from array if it's been clicked (and if it already has been previously added to an array)?

如何从数组中删除一个项目,如果它被点击(并且如果它之前已经被添加到一个数组中)?

我有一个 Framer X (React) 原型,它从 API 中提取足球博彩信息,如下所示:

const API = "https://api.myjson.com/bins/i461t"

// [1]
export const data = Data({
    matches: [],
    chosenBets: [],
})

// [2]
const fetchData = async (endpoint, callback) => {
    const response = await fetch(endpoint)
    const json = await response.json()
    data.matches = json
}

每场比赛都有与之相关的赔率:主客场以及平局:

当用户选择一个奇数时,它会突出显示并添加到 chosenBets 数组中:

export function PopulateMatches(): Override {
    return {
        matches: data.matches,
        onClick(obj, index) {
            data.chosenBets.splice(index, 1, obj)
            console.log(data.chosenBets, "data.chosenBets")
        },
    }
}

当我再次点击相同的奇数时,它被取消选择(红色背景从按钮中移除但不是数据对象chosenBets

如何从 chosenBets 数据对象中删除项目?

代码可以在这里查看:https://github.com/A7DC/FramerXTEST1

编辑:完整代码

import * as React from "react"
import { Data, Override, Stack, Frame } from "framer"
import { MatchCard } from "./canvas"

//// Pulling down mathches

const API = "https://api.myjson.com/bins/i461t"

// [1]
export const data = Data({
    matches: [],
    chosenBets: [],
})

// [2]
const fetchData = async (endpoint, callback) => {
    const response = await fetch(endpoint)
    const json = await response.json()
    data.matches = json
}

// App.tsx
export function PopulateMatches(): Override {
    return {
        matches: data.matches,
        onClick(obj, index) {
            data.chosenBets.splice(index, 1, obj)
            console.log(data.chosenBets, "data.chosenBets")
        },
    }
}

// [4]
fetchData(API, {})

Array.splice() 也可用于从数组中删除元素。

data.chosenBets.splice(index, 1); // Deletes the element at specified index.

此外,添加到 chosenBets 数组看起来不对。添加时第二个参数应该是 0

data.chosenBets.splice(index, 0, obj); // Adds the element at specified index.

那么 onClick() 函数看起来像

onClick(obj, index) {
  if (data.chosenBets[index]) {
    // Remove object.
    data.chosenBets.splice(index, 1);
  } else {
    // Add object.
    data.chosenBets.splice(index, 0, obj); 
  }
}