error TypeError: Cannot convert undefined or null to object

error TypeError: Cannot convert undefined or null to object

我在使用 axios 时遇到了这个错误,json 加载正常,但是渲染有问题

actions.js:

export const getUser = (callback)=>{
    return function(dispatch){
        dispatch({type: 'FETCH_GET_USER_REQUEST'});
        axios.get('https://jsonplaceholder.typicode.com/users')
        .then((response)=>{
            dispatch({type:'FETCH_GET_USER_SUCCES', payload:response.data});
            if (typeof callback === 'function') {
                callback(null, response.data)
            }
        })
    } 
}

reducerUser.js

export const getUserReducer = (state=[], action) =>{
    switch(action.type){
        case 'FETCH_GET_USER_REQUEST':
            return state;
        case 'FETCH_GET_USER_FAILURE':
            return state;   
        case 'FETCH_GET_USER_SUCCES':
            return [...action.payload.data];
        default:
            return state;
    }
}

container.jsx

class GetUserContainer extends Component{
    componentDidMount(){
        this.props.getUser();
    }
    render(){
        return(
            <GetUserComponent allUser={this.props.allUser} />
        )   
    }
}
function mapStateToProps(store){
        return{
            allUser:store.allUser
        }
}
function matchDispatchToProps(dispatch){
    return bindActionCreators({
        getUser:getUser
    }, dispatch)
}

store.js

 const store = createStore(
 reducers,
   applyMiddleware(thunk,  logger())
);

查看您的控制台输出,当 FETCH_GET_USER_SUCCES 操作被命中时,您的问题很可能出现在您的减速器中。

您正在 return 进行此操作:[...action.payload.data];。尝试记录您的负载,负载上可能没有数据对象,因此将 undefined 或 null 转换为对象错误。我打赌你只需要 return: [...action.payload];

从错误堆栈中,您可以看到错误是从代码中的 getUserReducer 调用的,然后是 _toConsumableArray 中调用的,这是在将扩展运算符转译为 es5 时由 babel 创建的辅助方法。

就像@ಠ_ಠ 暗示的那样,你得到错误是因为 action.payload.data 不是一个对象,在这种情况下应用扩展运算符将失败。 ([...action.payload.data])