描述: 每当我从使用 localhost 作为 API 端点切换到实际的后端实时 URL 时,我的 React 应用程序中都会遇到两个错误。以下是我遇到的错误:
PATCH https://hobby-hunter-api.onrender.com/users/6488a0ab682e930dcd661111/64628638beaa4cc4aecd3a42 404 (Not Found) in Friend.jsx:25 `Uncaught TypeError: friends.find is not a function in Friend.jsx:22
我使用 MongoDB 和 Node.js 作为后端。 感谢任何解决此问题的见解或解决方案。谢谢!
其他详细信息: 如果需要任何其他信息或代码片段来帮助诊断问题,请告诉我。
好友组件代码:
import { PersonAddOutlined, PersonRemoveOutlined } from "@mui/icons-material"; import { Box, IconButton } from "@mui/material"; import { useDispatch, useSelector } from "react-redux"; import { useNavigate } from "react-router-dom"; import { setFriends } from "state"; import UserImage from "./UserImage"; const Friend = ({ friendId, name, userPicturePath }) => { const dispatch = useDispatch(); const navigate = useNavigate(); const { _id } = useSelector((state) => state.user); const token = useSelector((state) => state.token); const friends = useSelector((state) => state.user.friends); const isFriend = friends && friends.find((friend) => friend._id === friendId); // Check if the friend exists const patchFriend = async () => { const response = await fetch( `https://weblinkbackendapi.onrender.com/users/${_id}/${friendId}`, { method: "PATCH", headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json", }, } ); const data = await response.json(); dispatch(setFriends({ friends: data })); }; if (!Array.isArray(friends)) { return null; // Return null if friends is not an array } return ( <Box className="text-black flex mb-2 bg-zinc-200 justify-between items-center rounded-lg z-10 ease-in duration-500"> <Box className="flex justify-between items-center gap-1"> <UserImage image={userPicturePath} /> <Box onClick={() => { navigate(`/profile/${friendId}`); navigate(0); }} > <h2 className="text-black font-medium hover:text-white cursor-pointer p-2 mr-1"> {name} </h2> </Box> </Box> <IconButton onClick={() => patchFriend()} sx={{ p: "0.05rem", fontSize: "0.25rem" }} > {isFriend ? ( <PersonRemoveOutlined sx={{ color: "grey" }} /> ) : ( <PersonAddOutlined sx={{ color: "grey" }} /> )} </IconButton> </Box> ); }; export default Friend;
我最终为当前用户的好友功能补丁添加了条件渲染。当当前用户请求自己时,问题就发生了。