Redux Reducer => 无法将 undefined 或 null 转换为对象

问题描述

所以我有一个很奇怪的错误,我不知道为什么或如何修复它。

Uncaught TypeError: Cannot convert undefined or null to object

所以这里有什么问题?我尝试将认状态直接添加到减速器中,我如何看到有关此错误的其他答案,但对我不起作用。

操作:

export const createProfile = profileValues => async dispatch => {
  const response = await profileApi.post('/profileApi',profileValues);

  dispatch({ type: CREATE_PROFILE,payload: response.data });
};

减速器:

const initialState = {
    values: {}
  };
  
  export default function(state = initialState,action) {
    switch (action.type) {
      case CREATE_PROFILE:
        return { ...state,[action.payload.id]: action.payload };
      default:
        return state;
    }
  }

组件:

const Profile = (props) => {

    useEffect(() => (props.createProfile()))

    return (
        'Return'
    );
};

const mapStatetoProps = state => {
    return { profile: Object.values(state.profile) };
  };
  
  export default connect(
    mapStatetoProps,{ createProfile }
  )(Profile);

解决方法

Object.values() 可以将 nullundefined 转换为具有它可以提取的属性的对象。

在 API 返回之前,mapStateToProps 选择器会尝试获取 state.profile 的值,即 undefined

const mapStateToProps = state => { 返回 { 配置文件:Object.values(state.profile) }; };

profile 的初始值设置为空对象:

const initialState = {
  values: {
    profile: {}
  }
};

Rr 在选择器级别使用回退值 - {}

return { profile: Object.values(state.profile ?? {}) };