我在下面的代码的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方法。我写了两个函数getPosts和getUserPosts来调用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)[{...},{...},{...},{...},{...},{...},{...}]
1条答案
按热度按时间6yjfywim1#
代码以错误的方式更新了
state.posts
。由于setPosts: (state, action) => { state.posts = action.payload.posts; },
需要更新代码如下:PostsWidget.jsx
字符串