【问题标题】:error TypeError: Cannot convert undefined or null to object错误类型错误:无法将未定义或空值转换为对象
【发布时间】:2016-12-16 22:22:45
【问题描述】:

我的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())
);

【问题讨论】:

  • 也许是return [...action.payload]; 而不是return [...action.payload.data];
  • @ಠ_ಠ 是的,你说得对吗,谢谢

标签: javascript reactjs redux dispatch axios


【解决方案1】:

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

您将返回这个:[...action.payload.data];。尝试记录您的有效负载,有效负载上可能没有数据对象,因此将 undefined 或 null 转换为对象错误。我打赌你只需要返回:[...action.payload];

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-17
      • 2015-05-09
      • 2021-08-13
      • 2020-03-28
      • 2020-06-09
      • 1970-01-01
      • 2020-12-22
      • 1970-01-01
      相关资源
      最近更新 更多