redux React,还原:未捕获的类型错误:无法读取未定义的属性(阅读'region')

zzwlnbp8  于 2022-11-12  发布在  React
关注(0)|答案(1)|浏览(131)

我正在将数据(对象)提取到redux状态,并在用户单击编辑时显示到文本区域:

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)
我是新的React和redux,所以任何帮助都非常感谢。谢谢!

xxe27gdn

xxe27gdn1#

最后我发现如果我在我所维滕的州名或减速器名的末尾使用“减速器”或“州”,my code runs with error
未捕获的类型错误:无法读取未定义的属性(阅读'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;
}

当我想访问另一个文件中的状态时,它会运行并显示该错误:

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

现在起作用了!:)

相关问题