【问题标题】:Displaying filtered data in React在 React 中显示过滤后的数据
【发布时间】:2021-12-19 00:09:52
【问题描述】:

好的,所以我最近有一个带回家的编码挑战,但我失败了。原因之一是我无法弄清楚如何使用复选框在 React 中实现过滤。所以我求助于使用 CSS 进行过滤,但他们希望我使用反应状态。

  const [data, setData] = useState([]);//api call data saved here
  const [publisher, setPublisher] = useState({// this state checks which checkboxes are selected or not
    Nin: false,
    MS: false,
    SN: false
  });

因此,对于作业,我必须进行 API 调用,这将在响应中为我提供 1000 多个项目。我必须过滤该对象,以便在 State 中仅保存 3 种类型的产品,这没有问题。

useEffect(() => {
    fetchJsonp("apicall", {
      jsonpCallback: "jsonp"
    })
      .then((response) => response.json())
      .then((json) =>
        setData(
          json.filter(
            (x) =>
              x["Publisher"] === "Nintendo" ||
              x["Publisher"] === "Sony" ||
              x["Publisher"] === "Microsoft"
          )
        )
      )
      .catch((err) => console.log(err));
  }, []);

问题在于,一旦卡片显示在屏幕上,它就会从当地状态吸收数据。用户可以选择通过复选框进行过滤,以仅查看 Nintendo、Microsoft 或 Sony 的产品类型,或者如果未选中复选框,则所有游戏都将显示。

所以我的问题是如何在 react 中实现这一功能?

【问题讨论】:

    标签: reactjs api filtering use-state


    【解决方案1】:

    只需在渲染中添加过滤器功能。我假设您使用的卡是map,所以只需执行类似的操作

    return (
      <>
        {data.filter((item)=>{
          const {Nin, MS, SN} = publisher;
          if(!Nin && !MS && !SN){ //return all if no boxes checked
            return true;
          }
          else{
            return (Nin && item.publisher === 'Ninetndo') || 
              (SN && item.publisher === 'Sony') || 
              (MS && item.publisher === 'Microsoft')
          }
        }).map((x) => <Card />)}
      </>
    )
    

    【讨论】:

    • 非常感谢。这正是你想要做的。
    猜你喜欢
    • 2022-11-23
    • 1970-01-01
    • 2021-08-08
    • 1970-01-01
    • 2019-05-24
    • 2022-01-22
    • 1970-01-01
    • 2021-06-07
    • 2017-05-04
    相关资源
    最近更新 更多