如何检测过滤器不工作的错误 reactjs

how to detect the bug of filter not working reactjs

您好,我使用 filter 单击“删除”按钮删除了我不需要的数据,但是没有用,也没有任何错误通知,所以我不知道如何检测我的项目.

import ColorCards from "./ColorCards";
import React, { useState } from "react";
import data from "./initialState.json";

export default function CardsafterEvents() {
  const [colors, setColors] = useState(data.colors);
  const onRemove = (id) => setColors(colors.filter((color) => color.id !== id));

  return (
    <>
      <ColorCards handleDelete={onRemove} />
    </>
  );
}

完整项目link:https://codesandbox.io/s/material-demo-forked-62eh0?file=/CardsafterEvents.js:0-379

您需要将 colors 传递给您的 ColorCards 元素

  • CardsafterEvents.js
export default function CardsafterEvents() {
  const [colors, setColors] = useState(data.colors);
  const onRemove = (id) => setColors(colors.filter((color) => color.id !== id));

  return (
    <>
      <ColorCards colors={colors} handleDelete={onRemove} />
    </>
  );
}

在你的 ColorCards 元素中,不仅使用来自 initialState 的数据,还从其父元素接收 colors prop,并优先与 useMemo 一起使用:

  • ColorCards.js
// ...
import React, { useMemo } from "react";
import data from "./initialState.json";

export default function ColorCards({ colors, handleDelete = (f) => f }) {
  const dataColors = useMemo(() => colors || data.colors, [colors]);

  return (...);
}

这是working example