javascript - 如何在 React/Framer 中查找数组中的特定项?

标签 javascript arrays reactjs framerjs

我正在从 API 中提取结果,如下所示:

  const [state, setState] = React.useState({

        matches: undefined,
        chosenBets: [{}]
      });


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

      const fetchData = async (endpoint, callback) => {
        const response = await fetch(endpoint);
        const json = await response.json();
        setState({ matches: json });
      };

并使用 map() 函数渲染基于它的 JSX:

export function MatchCardGroup(props) {
  return (
    <div>
      {props.matches.map((match, i) => {
        return (
          <MatchCard
            key={i}
            matchCardIndex={i}
            team_home={match.teams[0]}
            team_away={match.teams[1]}
            league_name={match.sport_nice}
            odd_home={match.sites[0].odds.h2h[0]}
            odd_draw={match.sites[0].odds.h2h[1]}
            odd_away={match.sites[0].odds.h2h[2]}
            onClick={props.onClick}
            timestamp={match.timestamp}
          />
        );
      })}
    </div>
  );
}

然后我有一张有赔率的卡片,每个赔率都有自己的点击事件:

export function MatchCard(props) {
  const [state, setState] = React.useState({
    selection: {
      id: undefined
    }
  });

  const {
    timestamp,
    team_home,
    team_away,
    league_name,
    odd_away,
    odd_draw,
    odd_home,
    onClick,
    matchCardIndex,
    selection
  } = props;

  const odds = [
    {
      id: 0,
      label: 1,
      odd: odd_home || 1.6
    },
    {
      id: 1,
      label: "X",
      odd: odd_draw || 1.9
    },
    {
      id: 2,
      label: 2,
      odd: odd_away || 2.6
    }
  ];

  const handleOnClick = (odd, oddIndex) => {
    // need to changhe the selection to prop
    if (state.selection.id === oddIndex) {
      setState({
        selection: {
          id: undefined
        }
      });
      onClick({}, matchCardIndex);
    } else {
      setState({
        selection: {
          ...odd,
          team_home,
          team_away
        }
      });
      onClick({ ...odd, oddIndex, team_home, team_away, matchCardIndex });
    }
  };

  React.useEffect(() => {}, [state, props]);

  return (
    <div style={{ width: "100%", height: 140, backgroundColor: colour.white }}>
      <div>
        <span
          style={{
            ...type.smallBold,
            color: colour.betpawaGreen
          }}
        >
          {timestamp}
        </span>
        <h2 style={{ ...type.medium, ...typography }}>{team_home}</h2>
        <h2 style={{ ...type.medium, ...typography }}>{team_away}</h2>
        <span
          style={{
            ...type.small,
            color: colour.silver,
            ...typography
          }}
        >
          {league_name}
        </span>
      </div>

      <div style={{ display: "flex" }}>
        {odds.map((odd, oddIndex) => {
          return (
            <OddButton
              key={oddIndex}
              oddBackgroundColor={getBackgroundColour(
                state.selection.id,
                oddIndex,
                colour.lime,
                colour.betpawaGreen
              )}
              labelBackgroundColor={getBackgroundColour(
                state.selection.id,
                oddIndex,
                colour.lightLime,
                colour.darkBetpawaGreen
              )}
              width={"calc(33.3% - 8px)"}
              label={`${odd.label}`}
              odd={`${odd.odd}`}
              onClick={() => handleOnClick(odd, oddIndex)}
            />
          );
        })}
      </div>
    </div>
  );
}

在我的 App 组件中,我正在记录点击事件返回的对象:

  const onClick = obj => {
    // check if obj exists in state.chosenBets
    // if it exists, remove from array
    // if it does not exist, add it to the array
    if (state.chosenBets.filter(value => value == obj).length > 0) {
      console.log("5 found.");
    } else {
      console.log(state.chosenBets, "state.chosenBets");
    }
  };

我想做的是:

  1. 当用户点击任何给定比赛的赔率时,将该赔率添加到 chosenBets
  2. 如果用户取消选择赔率,请从 chosenBets 中删除该赔率
  3. 任何比赛的 3 个可能赔率中,每次只能选择 1 个赔率

奖励积分:所选择的赔率是根据App的全局状态而不是本地状态来选择的。因此,如果我在其他地方编辑数组,它应该在 UI 中更新。

任何帮助将不胜感激,我在这里迷路了!

Link to Codesandbox

最佳答案

我简要浏览了您的项目,以下是一些可以帮助您解决问题的建议:

对象仅通过引用才相等。

这意味着

{ id: 0, matchCardIndex: 8 } === { id: 0, matchCardIndex: 8 } 

是假的,即使您期望它是真的。要比较它们,您需要比较对象中的每个键:

value.id === obj.id && value.matchCardIndex === obj.matchCardIndex

这也会影响 index.tsx 中的过滤器调用,因此您应该将那里的比较更改为类似的内容

state.chosenBets.filter(value => value.id === obj.id && value.matchCardIndex === obj.matchCardIndex)

状态应该只存在于一个地方

正如您已经提到的,如果您也需要状态,最好将状态保留在 index.tsx 中,并且不要将其本地保存在树中更靠下的组件中。我建议让组件只渲染状态,并使用处理程序来更改状态。

示例

这是您的代码沙箱的一个分支,我认为以您描述的方式实现它:https://codesandbox.io/s/gifted-star-wg629-so-pg5gx

关于javascript - 如何在 React/Framer 中查找数组中的特定项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58146483/

相关文章:

Javascript Replace() 和 innerHTML

javascript - 根据从下拉列表中选择的值显示文本框

javascript - 一个 HTML 页面上的多个 Three.js CSS3D 场景,分子示例

java - BinarySearch 与 For 循环

javascript - 浏览器内的 javascript 无法同时识别 "import"和 JSX

javascript - 更改div样式时如何进行平滑更改

javascript - 找出数组是否包含javascript中的算术级数

php - 如何将字符串插入数据库表中的不同列?

css - 我可以在 React 中使用样式化组件实现以下条件媒体查询吗?

reactjs - redux-saga 中的重试功能