React Redux工具包

发布于 2025-02-04 13:27:37 字数 1583 浏览 0 评论 0 原文

我有Postsslice,可从服务器提供有关帖子的数据 在此处输入图像描述

PostSlice Code

const initialState = {
  posts: [],
};

const post = createSlice({
  name: "post",
  initialState,
  reducers: {
    getPosts(state, action) {
      state.posts = action.payload.posts;
    },
  },
});

const { getPosts } = post.actions;

export function GetPostByInterests() {
  return async (dispatch) => {
    try {
      const response = await API.get("/posts", {
        params: {
          limit: 10,
          offset: 0,
        },
      });
      const data = response.data;
      const posts = data.data;

      dispatch(
        getPosts({
          posts: posts,
        })
      );
    } catch (e) {}
  };
}

我正在尝试在前端拉出用户的图像在明信片中,我会收到一个错误:undurect typeError:posts.author.avatar是未定义的

前端代码

export const News = () => {
  const dispatch = useDispatch();
  const posts = useSelector((state) => state.post.posts);
 
  useLayoutEffect(() => {
    dispatch(GetPostByInterests());
  }, []);

  return (
    <div className="container-md shadow-lg bg-white py-10 px-8 mx-[5rem] my-[1rem] rounded-md">
      {posts.map((posts) => (
        <PostCard key={posts.id} posts={posts} />
      ))}
    </div>
  );
};

明信片前端图像显示:

        <img
          className="w-12 h-12 rounded-full object-cover mr-4 shadow"
          src={posts.author.avatar.url}
          alt="avatar"
        ></img>

I have PostsSlice which provides data from server about posts
enter image description here

PostSlice Code:

const initialState = {
  posts: [],
};

const post = createSlice({
  name: "post",
  initialState,
  reducers: {
    getPosts(state, action) {
      state.posts = action.payload.posts;
    },
  },
});

const { getPosts } = post.actions;

export function GetPostByInterests() {
  return async (dispatch) => {
    try {
      const response = await API.get("/posts", {
        params: {
          limit: 10,
          offset: 0,
        },
      });
      const data = response.data;
      const posts = data.data;

      dispatch(
        getPosts({
          posts: posts,
        })
      );
    } catch (e) {}
  };
}

I'm trying to pull out the user's image in the frontend in the post card and I get an error: Uncaught TypeError: posts.author.avatar is undefined

FrontEnd Code

export const News = () => {
  const dispatch = useDispatch();
  const posts = useSelector((state) => state.post.posts);
 
  useLayoutEffect(() => {
    dispatch(GetPostByInterests());
  }, []);

  return (
    <div className="container-md shadow-lg bg-white py-10 px-8 mx-[5rem] my-[1rem] rounded-md">
      {posts.map((posts) => (
        <PostCard key={posts.id} posts={posts} />
      ))}
    </div>
  );
};

PostCard FrontEnd image display:

        <img
          className="w-12 h-12 rounded-full object-cover mr-4 shadow"
          src={posts.author.avatar.url}
          alt="avatar"
        ></img>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

左秋 2025-02-11 13:27:37

welcom to stackoverflow @memphis

您需要使用 src img 标签中。像这样:

<img
  className="w-12 h-12 rounded-full object-cover mr-4 shadow"
  src={posts?.author.avatar.url}
  alt="avatar"
></img>

最好使用映射来自API的数据时,以避免获取数据时遇到未定义的错误:

// If posts aren't loaded yet, show a message
// (Or you can even show a loading spinner)
{!posts?.length ? <p>Nothing to Show</p> : posts.map((posts) => (
  <PostCard key={posts.id} posts={posts} />
))}

Welcom to Stackoverflow @memphis

You need to use Optional Chaining in the src of the img tag. Like this:

<img
  className="w-12 h-12 rounded-full object-cover mr-4 shadow"
  src={posts?.author.avatar.url}
  alt="avatar"
></img>

It's also good practice to use a Ternary Operator when mapping through the data that is coming from the API, in order to avoid getting undefined errors when the data is being fetched:

// If posts aren't loaded yet, show a message
// (Or you can even show a loading spinner)
{!posts?.length ? <p>Nothing to Show</p> : posts.map((posts) => (
  <PostCard key={posts.id} posts={posts} />
))}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文