【问题标题】:How to find specific items in an array in React/Framer?如何在 React/Framer 的数组中查找特定项目?
【发布时间】:2019-09-28 12:50:35
【问题描述】:

我正在从 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

【问题讨论】:

    标签: javascript arrays reactjs framerjs


    【解决方案1】:

    我对您的项目进行了简短的了解,以下是一些可以帮助您的建议:

    对象只有通过引用才能相等。

    这意味着

    { 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

    【讨论】:

    • 谢谢,尼尔斯。无论如何,我对此进行了排序,但忘记了我已将其发布在这里。感谢您的帮助,我很感激! ?
    猜你喜欢
    • 1970-01-01
    • 2019-01-06
    • 2021-11-09
    • 2016-10-30
    • 2021-06-24
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多