简体   繁体   English

useSelector 属性返回未定义

[英]useSelector property returns undefined

I'm trying to fetch 'all posts' using Redux. I should be getting an empty array but instead, I'm getting undefined.我正在尝试使用 Redux 获取“所有帖子”。我应该得到一个空数组,但相反,我变得不确定。 Here's my reducer:这是我的减速器:

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

    default:
      return posts;
  }
}; 

Action行动


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

According to your reducer, your entire state is a posts array instead of a state object like { posts: [ ] }.根据您的减速器,您的整个 state 是一个 posts 数组,而不是像 { posts: [ ] } 这样的 state object。 So in your selector, you can simply return the state as it is in the Posts component.因此,在您的选择器中,您可以简单地返回 state,因为它在 Posts 组件中。

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

I believe that you need to change a line in your reducer file.我相信您需要更改 reducer 文件中的一行。 You need to assign the action.payload to the posts and then you can access it您需要将 action.payload 分配给帖子,然后您才能访问它

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

    default:
      return posts;
  }
}; 
  1. Firstly, switch ((action.type)) should be switch (action.type)首先, switch ((action.type))应该是switch (action.type)
  2. Then, you should check the data from api whether it's returned correctly or not然后,您应该检查api的data是否正确返回
  3. Finally, check your redux state object and your selector of posts最后,检查您的 redux state object 和您的posts选择器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM