首页 > 解决方案 > 尝试绘制没有重复的数据

问题描述

我是这里的初学者!我正在尝试使用此 data.JSON 按流派部分创建过滤,如下所示:

  "movies": [
    {
      "title": "The Shawshank Redemption",
      "release": "1994",
      "rating": "9.2",
      "genre": "Drama",
      "id": 1
    },
    {
      "title": "The Godfather",
      "release": "1972",
      "rating": "9.1",
      "genre": "Crime Drama",
      "id": 2
    },
    {
      "title": "The Godfather Part II",
      "release": "1974",
      "rating": "9",
      "genre": "Crime Drama",
      "id": 3
    },
    {
      "title": "The Dark Knight",
      "release": "2008",
      "rating": "9",
      "genre": "Action",
      "id": 4
    },
    {
      "title": "Howl's Moving Castle ",
      "release": "2001",
      "rating": "9.5",
      "genre": "Animation",
      "id": 5
    }]

下面是我当前对 map 方法的实现,但结果是类型有重复(两部犯罪剧)

我正在尝试过滤掉重复项。我该怎么做呢?

import useFetch from "./useFetch";

const MovieList = () => {
  const { data, isPending, error, setData } = useFetch(
    "http://localhost:8002/movies"
  );

return (
    <div className="movie-list">
      
      <div className="row">
        <div className="col-2">
          <ul className="list-group">
            <li className="list-group-item">All Genre</li>
            {data.map((item) => {
                return (
                  <li
                    key={item.id}
                    onClick={handleFilterGenre}
                    className="list-group-item"
                  >
                    {item.genre}
                  </li>
                );
              })}
          </ul>
        </div>

任何帮助深表感谢!谢谢

标签: javascriptreactjs

解决方案


试试这种方法:(一个包含已经编写的流派的外部数组 - 用于过滤)

import useFetch from "./useFetch";

const MovieList = () => {
  const { data, isPending, error, setData } = useFetch(
    "http://localhost:8002/movies"
  );

const displayedGenres = [];

return (
    <div className="movie-list">
      
      <div className="row">
        <div className="col-2">
          <ul className="list-group">
            <li className="list-group-item">All Genre</li>
            {data.map((item) => {
                if (displayedGenres.includes(item.genre))
                   return;
                else {
                displayedGenres.push(item.genre);
                return (
                  <li
                    key={item.id}
                    onClick={handleFilterGenre}
                    className="list-group-item"
                  >
                    {item.genre}
                  </li>
                );
               }
              })}
          </ul>
        </div>

推荐阅读