redux 为什么组件没有通过useEffect更新?

u7up0aaq  于 2023-08-05  发布在  其他
关注(0)|答案(1)|浏览(110)

我在下面的代码的UI中看不到<PostWidget/>

PostsWidget.jsx

import { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { setPosts } from "../../../Redux/Slices/authSlice";
import PostWidget from "../PostWidget";
import { userRequest } from "../../../requestMethod";

const PostsWidget = ({ userId, isProfile = false }) => {
  const dispatch = useDispatch();
  const posts = useSelector((state) => state.posts);
  console.log("posts", posts);

  const getPosts = async () => {
    const res = await userRequest.get("/posts");
    console.log("all Posts", res.data);
    dispatch(setPosts(res.data));
  };

  const getUserPosts = async () => {
    const res = await userRequest.get(`/${userId}/posts`);
    console.log("user Post", res.data);
    dispatch(setPosts(res.data));
  };

  useEffect(() => {
    if (isProfile) {
      getUserPosts();
    } else {
      getPosts();
    }
  }, []);

  return (
    <>
      {posts && posts.map(
        ({
          _id,
          userId,
          firstName,
          lastName,
          description,
          location,
          picturePath,
          userPicturePath,
          likes,
          comments,
        }) => (
          <PostWidget
            key={_id}
            postId={_id}
            postUserId={userId}
            name={`${firstName} ${lastName}`}
            description={description}
            location={location}
            picturePath={picturePath}
            userPicturePath={userPicturePath}
            likes={likes}
            comments={comments}
          />
        )
      )}
    </>
  );
};

export default PostsWidget;

字符串

PostWidget.jsx

const PostWidget = () => {
  return (
    <div>
      <h4>Post Widget</h4>
    </div>
  );
};

export default PostWidget;


这里,userRequest是一个axios方法。我写了两个函数getPostsgetUserPosts来调用API

AuthSlice.js

import { createSlice } from "@reduxjs/toolkit";
const initialState = {
  mode: "light",
  user: null,
  token: null,
  posts: [],
};      
export const authSlice = createSlice({
  name: "auth",
  initialState,
  reducers: {                 
 setPosts: (state, action) => {
      state.posts = action.payload.posts;
    },
    setPost: (state, action) => {
      const updatedPosts = state.posts.map((post) => {
        if (post._id ===action.payload.post._id) {
          return action.payload.post;
        }
        return post;
      });
      state.posts = updatedPosts;
    },
  },
});


我用redux devtool检查了console.logs和redux状态。两者都显示更新的posts控制台日志
所有帖子(7)[{...},{...},{...},{...},{...},{...},{...}]

6yjfywim

6yjfywim1#

代码以错误的方式更新了state.posts。由于setPosts: (state, action) => { state.posts = action.payload.posts; },需要更新代码如下:

PostsWidget.jsx

const getPosts = async () => {
    const res = await userRequest.get("/posts");
    console.log("all Posts", res.data);
    dispatch(setPosts({ posts: res.data }));
  };

  const getUserPosts = async () => {
    const res = await userRequest.get(`/${userId}/posts`);
    console.log("user Post", res.data);
    dispatch(setPosts({ posts: res.data }));
  };

字符串

相关问题