【问题标题】:useSelector property returns undefineduseSelector 属性返回未定义
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    我相信您需要更改 reducer 文件中的一行。您需要将 action.payload 分配给帖子,然后您才能访问它

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

    【讨论】:

      【解决方案3】:
      1. 首先,switch ((action.type))应该是switch (action.type)
      2. 然后,你应该检查来自api的data是否被返回 正确与否
      3. 最后,检查你的 redux 状态对象和你的 posts 选择器

      【讨论】:

        猜你喜欢
        • 2021-10-10
        • 1970-01-01
        • 1970-01-01
        • 2023-02-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多