我试图从数组中删除一个对象,但得到的响应是数据未定义

I'm trying to delete an object from an array and the response I get is that the data is undefined

我是编码新手,遇到了一些问题,需要一些帮助,如果有人能帮助我解决这个问题,我将不胜感激。 首先,我使用 react.js 来构建我的应用程序,然后 我使用 npm json.server 做了一个假休息 api。代码中的每一步都有效,但方法 DELETE 无效,并且无法从数组中删除对象。 在我的 VS 终端中,我收到这样的 404 响应 DELETE /albums/undefined 404。 所以我认为它无法看到数组中的数据。

删除方法如下所示:

const onDelete = async (id) => {
    await fetch(`http://localhost:3500/albums/${id}`, {
      method: "DELETE",
    })
      .then((res) => {
        console.log(res.json);
        if (res.status !== 200) {
          return;
        } else {
          setUsers(
            albums &&
              albums.filter((album) => {
                return album.id !== id;
              })
          );
        }
      })
      .catch((err) => {
        console.log(err);
      });
    // console.log(data);
  };

现在我可以 post 我的完整功能 这是我的职能:

import "./App.css";
import AddUser from "./components/adduser/AddUser";
import User from "./components/users/User";

const App = () => {
  const [albums, setUsers] = useState([]);
  const [genres, setGen] = useState([]);
  useEffect(() => {
    fetchData();
    fetchGenres();
  }, []);

const fetchData = async () => {
    await fetch("http://localhost:3500/albums")
      .then((res) => {
        if (res.ok) {
          console.log("everthing is OK!");
        } else {
          console.log("Somethig went wrong");
        }
        return res;
      })
      .then((res) => res.json())
      .then((data) => setUsers(data))
      .catch((err) => {
        console.log(err);
      });
  };

const fetchGenres = async () => {
    await fetch("http://localhost:3500/genres")
      .then((res) => {
        if (res.ok) {
          console.log("everthing is OK!");
        } else {
          console.log("Somethig went wrong");
        }
        return res;
      })
      .then((res) => res.json())
      .then((value) => setGen(value))
      .catch((err) => {
        console.log(err);
      });
  };

const onAdd = async (name, band, city, genresId) => {
    await fetch("http://localhost:3500/albums", {
      method: "POST",
      body: JSON.stringify({
        name: name,
        band: band,
        city: city,
        genresId: parseInt(genresId),
      }),
      headers: {
        "content-type": "application/json;charset=UTF-8",
      },
    })
      .then((res) => {
        // console.log(res.method);
        if (res.status !== 201) {
          return;
        } else {
          return res.json();
        }
      })
      .then((data) => {
        setUsers((albums) => [data, ...albums]);
      })
      .catch((err) => {
        console.log(err);
      });
  };

const onDelete = async (id) => {
    await fetch(`http://localhost:3500/albums/${id}`, {
      method: "DELETE",
    })
      .then((res) => {
        console.log(res.json);
        if (res.status !== 200) {
          return;
        } else {
          setUsers(
            albums &&
              albums.filter((album) => {
                return album.id !== id;
              })
          );
          console.log(res.album);
        }
      })
      .catch((err) => {
        console.log(err);
      });
  };

return (
    <div className="App">
      <h3>Bands Albums & Genres</h3>
      <br />
      <AddUser onAdd={onAdd} values={genres} />

      <div>
        {albums &&
          albums.map((album) => (
            <User
              name={album.name}
              band={album.band}
              city={album.city}
              genresId={
                genres &&
                genres.map((g) => {
                  if (g.id === album.genresId) {
                    return g.name;
                  }
                  return "";
                })
              }
              onDelete={onDelete}
            />
          ))}
      </div>
    </div>
  );

我的数组结构如下所示:

{
  "albums":[
   {
      "name": "albumName1",
      "band": "BandName1",
      "city": "City",
      "id": 0,
      "genresId": 0
    },
    {
      "name": "albumName2",
      "band": "BandName2",
      "city": "City",
      "id": 1,
      "genresId": 0
    },
    {
      "name": "albumName3",
      "band": "BandName3",
      "city": "City",
      "id": 2,
      "genresId": 3
    }
],
"genres": [
    {
      "id": 0,
      "name": "grunge"
    },
    {
      "id": 1,
      "name": "rock"
    },
    {
      "id": 2,
      "name": "jazz"
    },
    {
      "id": 3,
      "name": "pop"
    },
  ]
}

这是我用于渲染的组件:

const User = ({ id, name, band, city, genresId, onDelete }) => {
  const handleDelete = () => {
    onDelete(id);
  };

  return (
    <div className="list">
      <span>{name}</span>
      <span>{band}</span>
      <span>{city}</span>
      <span>{genresId}</span>

      <span>
        <button onClick={handleDelete}>delete</button>
      </span>
    </div>
  );
};

我在函数中还有更多组件,但我认为它们对我要完成的工作没有任何影响。

控制台记录 onDelete 函数中的 id,您将看到它是 undefined。这就是调用端点 /albums/undefined 的原因。

return (
    ...
    onDelete={onDelete} // the problem is here
    ...
);

进一步阅读:https://reactjs.org/docs/faq-functions.html#how-do-i-pass-a-parameter-to-an-event-handler-or-callback

您收到错误消息是因为您没有将 id 属性传递给 <User /> 组件。

试试这个

           <User
              name={album.name}
              band={album.band}
              city={album.city}
              id={album.id}               <----- Add this line
              genresId={
                genres &&
                genres.map((g) => {
                  if (g.id === album.genresId) {
                    return g.name;
                  }
                  return "";
                })
              }
              onDelete={onDelete}
            />