【发布时间】:2022-11-16 18:31:12
【问题描述】:
我正在尝试使用 Redux 获取“所有帖子”。我应该得到一个空数组,但相反,我变得不确定。这是我的减速器:
export default (posts = [], action) => {
switch ((action.type)) {
case "FETCH_ALL":
return action.payload;
case "CREATE":
return posts;
default:
return posts;
}
};
行动
export const getPosts = () => async (dispatch) => {
try {
const { data } = await api.fetchPosts();
dispatch({ type: "FETCH_ALL", payload: data });
} catch (error) {
console.log(error.message)
}
};
Posts.js 组件
import { useSelector } from "react-redux";
import Post from "./Post/Post";
import useStyles from "./styles";
const Posts = () => {
const posts = useSelector((state)=>state.posts)
console.log(posts)
const classes = useStyles();
return (
<>
<h1>Posts</h1>
<Post />
</>
);
};
export default Posts;
【问题讨论】:
-
“useState 属性返回未定义”您的问题文本中没有显示单个
useState。 -
您还可以向我们展示您的商店文件和 Combine reducer,如果那是不同的文件的话?
-
@T.J.Crowder 感谢您指出,我的意思是 useSelector
标签: javascript reactjs redux frontend