redux useSelector属性返回未定义的

ocebsuys  于 2022-11-24  发布在  其他
关注(0)|答案(3)|浏览(154)

我试图用Redux获取'all post'。我应该得到一个空数组,但却得到了一个未定义的数组。下面是我的reducer:

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;
xeufq47z

xeufq47z1#

根据您的reducer,您的整个状态是一个posts数组,而不是像{ posts:[ ] }。因此,在选择器中,您可以简单地返回Posts组件中的状态。

const posts = useSelector((state)=>state);
ki0zmccv

ki0zmccv2#

我相信你需要修改你的reducer文件中的一行。你需要把action.payload分配给post,然后你就可以访问它了

export default (posts = [], action) => {
  switch ((action.type)) {
    case "FETCH_ALL":
      return {posts: action.payload};
    case "CREATE":
      return posts;

    default:
      return posts;
  }
};
vyu0f0g1

vyu0f0g13#

1.首先,switch ((action.type))应该是switch (action.type)
1.然后,您应该检查来自api的data是否正确返回
1.最后,检查redux状态对象和posts选择器

相关问题