使用即時伺服器但不使用本機時發生錯誤:'friends.find 不是函數”
P粉489081732
P粉489081732 2023-09-11 10:37:04
0
1
579

描述: 每當我從使用 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;

P粉489081732
P粉489081732

全部回覆(1)
P粉928591383

我最終為目前使用者的好友功能補丁添加了條件渲染。噹噹前用戶請求自己時,問題就發生了。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板