【问题标题】:Redux state becomes undefinedRedux 状态变为未定义
【发布时间】:2021-05-06 01:50:42
【问题描述】:

我一直在学习 redux,但在选择器调用期间我的状态返回 undefined 时遇到问题。

一些代码:

选择器: export const selectPosts = reduxState => reduxState.posts.myPost

行动:

export const addPosts = ({ subId, postId, userId, content }) => ({
  type: "posts/add",
  payload: {
    userId,
    postId,
    content,
    subId
  },
});

减速机:

const myPost = [],
      
  
  
export default function reducer(state = myPost, action) {
    switch (action.type) {
      case "posts/add": {
        return {
            
          ...state,
          myPost: [
            ...state.posts,
            {
              userId: action.payload.userId,            
              postId: action.payload.postId,
              content: action.payload.content,
              subId: action.payload.subId,
              
            },
          ],
        };
      }
      default: {
        return state;
      }
    }
  }
  

我用const posts = useSelector(selectPosts);调用选择器

我看了很多,虽然有很多问题与我的问题相同,但我无法取得任何进展。

我认为这可能与我阅读对象的方式有关,但我还没有解决它

谢谢

Samuele-png

编辑:我收到的错误如下:

TypeError: Cannot read property 'myPost' of undefined

selectPosts
src/store/posts/selectors.js:1
> 1 | export const selectPosts = reduxState => reduxState.post.myPost
View compiled

▶ 2 stack frames were collapsed.

FrontPage
src/pages/FrontPage.js:10
   7 | import { useDispatch } from "react-redux";
   8 | 
   9 | export default function FrontPage() { 
> 10 | const posts = useSelector(selectPosts);
  11 | console.log(posts)
  12 |   return (
  13 |     <div> 

还有商店

import userReducer from "./user/reducer";
import postReducer from "../posts/reducer";

import { createStore, applyMiddleware, compose, combineReducers } from "redux";
import ReduxThunk from "redux-thunk";

const devTools = window.__REDUX_DEVTOOLS_EXTENSION__
  ? window.__REDUX_DEVTOOLS_EXTENSION__()
  : (x) => x;

const enhancer = compose(applyMiddleware(ReduxThunk), devTools);
const store = createStore(
  combineReducers({
    user: userReducer,
    team: postReducer,
  }),
  enhancer
);

export default store;

【问题讨论】:

  • 您将 initialState 作为数组 state=myPosts 开始,然后在您的帖子/添加操作中返回一个对象 - return {...state, myPost: []}
  • 你能分享数据在你的 redux 状态下是如何存储的吗?
  • 嘿!你的意思是 store.js 吗?我把它添加到主帖
  • 您正在将 postReducer 重命名为 team。因此,在选择时,您必须通过该名称引用它。 const post = useSelector(state => state.team)
  • 嘿 abishek 非常感谢你,为我解决了这个问题。我不敢相信我被困了几个小时,而答案就在我面前。非常感谢!!!!!!

标签: javascript reactjs redux react-redux


【解决方案1】:

您正在将您的帖子映射到 combineReducers 中的团队,因此您必须通过该键在 useSelectors 中引用。
const posts = useSelector(state =&gt; state.team) 也不要更改传递给减速器的 initialState 的类型 您的帖子减速器中的示例, 您正在传递一个数组 myPost 作为 initialState 但后来从减速器返回一个对象,它可以欢迎更多的错误。

【讨论】:

    猜你喜欢
    • 2021-12-16
    • 1970-01-01
    • 2016-12-22
    • 2019-04-07
    • 1970-01-01
    • 1970-01-01
    • 2018-09-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多