我在redux状态下将帖子定义为数组,但当我试图将其Map到组件代码中时,它似乎不起作用。下面是我的Redux状态代码:
import {createSlice} from "@reduxjs/toolkit";
const initialState = {
mode:"light",
user:null,
token:null,
posts:[]
};
export const authSlice = createSlice({
name:"auth",
initialState,
reducers:{
setMode: (state)=>{
state.mode = state.mode === "light" ? "dark":"light"
},
setLogin: (state,action)=>{
state.user = action.payload.user;
state.token = action.payload.token;
},
setLogout:(state)=>{
state.user = null;
state.token = null;
},
setFriends:(state,action)=>{
if(state.user){
state.user.friends = action.payload.friends
}
else{
console.error("User friends non-exsistant")
}
},
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;
}
}
})
export const {setMode , setLogin ,setLogout,setFriends,setPosts,setPost}= authSlice.actions;
export default authSlice.reducer;
这是我的组件代码,我已经正确地使用了Useselector()
函数来抓取posts数组,但它仍然给出了错误,Map()
不是一个函数,我也正确地实现了Redux,并将我的应用程序 Package 在Provider标签中。
const PostsWidget = ({ userId, isProfile = false }) => {
const dispatch = useDispatch();
const posts = useSelector((state)=> state.posts);
const token = useSelector((state) => state.token);
Here is the map code
`return (
<>
{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}
/>
)``
我本以为它能工作,但不知道为什么它给了我一个错误。
1条答案
按热度按时间krcsximq1#
感谢您发送编修。看起来你的代码中有一个小的错别字。
密码:
正确代码:
注意
_id
前面的点。顺便说一句,这在教程中提到了5:06:50:https://youtu.be/K8YELRmUb5o?t=18410
希望这能帮上忙