繁体   English   中英

反应,Redux:未捕获的类型错误:无法读取未定义的属性(读取“区域”)

[英]React, Redux: Uncaught TypeError: Cannot read properties of undefined (reading 'region')

我正在将数据(一个对象)提取到 redux state 并在用户单击编辑时显示到 textarea 中:

const regionData = useSelector((state) => state.myReducer.userDetailList.region);

但第一次它给了我以下错误:

Uncaught TypeError: Cannot read properties of undefined (reading 'region')

当我根据 eslint 建议更改代码时也发生了这个错误:

i.e. 
Use an object spread instead of `Object.assign` eg: `{ ...foo }`

旧代码:

return Object.assign({}, state, {
    userDetailList: {
        region: action.userDetailsPayload.region,
    },
});

新代码:

 const userDetailList = {
     region: action.userDetailsPayload.region,
 };

 return { ...state, ...userDetailList };

结果 userDetailList 在 Chrome redux-devtool 中显示为空白。 它使用旧代码(Object.assign)

我是新来的反应和 redux,所以非常感谢任何帮助。 谢谢!

我有一个同样的问题。 最后我发现如果我在状态名称或我所写的减速器名称的末尾使用术语“Reducer”或“State”,我的代码会运行错误

未捕获的类型错误:无法读取未定义的属性(读取“result_201”)

我的减速机:

    export function netInfoRecordReducer (
    state = initialStateNetInfoRecord,
    action : Actions
  ) : NetInfoRecordState {
    switch (action.type) {
      case SET_NET_INFO_RECORD: {
        if ( action.payload.RESULT === "SUCCESS") {
          return {
            ...state,
            result_201: action.payload.RESULT_CONTENT,
          };
        }
        return state;
      }
      default:
        return state;
    }
  }

以及用于定义 CobineReducer 和 RoutState 的 index.tsx 文件:

export default combineReducers({
  netInfoRecordReducer: netInfoRecordReducer,
});

export interface RootState {
  netInfoRecordState: NetInfoRecordState;
}

当我想访问另一个文件中的 state 时,它会出现该错误:

    const netInfoRecord = useAppSelector( (state) => 
        state.netInfoRecord.result_201);
    console.log(netInfoRecord);

但是如果我删除“State”和“Reducer”术语并将我的 index.tsx 文件更改为:

    export default combineReducers({
      netInfoRecord: netInfoRecordReducer,
    });

    export interface RootState {
     netInfoRecord: NetInfoRecordState;
    }

现在可以了::)

暂无
暂无

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

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