【问题标题】:(TypeError: Cannot read property 'find' of undefined)(类型错误:无法读取未定义的属性“查找”)
【发布时间】:2020-03-28 04:42:14
【问题描述】:

我想将我的 redux store id 与 action payload id 进行比较,并使用 find 方法更新我的 redux store 状态。当我第三次比较相同的值时,find 方法只工作两次,所以 find 方法给了我这个错误:

TypeError: 无法读取未定义的“查找”属性

const initialState = {
  frontendCategory: [],
  backendCategory: [],
  devOpsCategory: [],
};

const reducer = (state = initialState, action) => {
  switch (action.type) {
    case actionTypes.ADDED_USER_TO_FRONTEND_CATEGORY:
      let updateddata = state.frontendCategory.find(data => data.id === action.payLoad.id);

      if (updateddata) {
        return [...state.frontendCategory];
      }

      return {
        ...state,
        frontendCategory: state.frontendCategory.concat(action.payLoad),
      };
  }
};

export const addedUserToFrontendCategory = (GithubUserId) => {
  return {
    type: actionTypes.ADDED_USER_TO_FRONTEND_CATEGORY,
    payLoad: {
      id: GithubUserId,
    },
  };
};

【问题讨论】:

  • if(updateddata){ return [...state.frontendCategory] } 你只是想检查frontendCategory 中是否已经存在 id 吗?因为变量名updateddata 让我很困惑。
  • 因为如果是这样的话,我想你想返回整个状态if(updateddata) { return state }
  • 是的,它对我有用!!非常感谢!!!

标签: reactjs redux react-redux state


【解决方案1】:

当您的 updateddata 变为 true 时,您将状态从包含 frontendCategory 的对象更改为包含来自 frontendCategory 的属性的数组。

发生这种情况时,您会收到此错误,因为您的状态现在是一个数组,并且没有 frontendCategory 作为属性。

也许你应该总是返回一个对象。像这样的:

if (updateddata) {
        return state; // or return your business rule, but always an object contains frontendCategory as an array
      }

      return {
        ...state,
        frontendCategory: state.frontendCategory.concat(action.payLoad),
      };

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-29
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    • 2021-11-22
    • 2017-08-12
    相关资源
    最近更新 更多