繁体   English   中英

我正在尝试从数组中删除 object,得到的响应是数据未定义

[英]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 制作了一个假的 rest api。 代码中的每一步都有效,但方法 DELETE 无效,并且无法从数组中删除 object。 在我的 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);
  };

现在我可以发布完整的 function 这是我的 function:

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>
  );
};

我在 function 中还有一些组件,但我认为它们对我要实现的目标没有任何影响。

您收到错误是因为您没有将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}
            />

控制台日志 what is id from onDelete function 你会看到它是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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM