撷取资料时无法读取未定义的属性'map'

时间:2019-05-07 07:32:05

标签: reactjs redux react-redux

我正在尝试从API提取用户数据。我遇到的错误是:

  

在获取数据时无法读取未定义的属性“地图”

我阅读并检查了许多示例,其他示例做了什么。似乎很容易理解,但由于我是新手,所以无法找出错误的出处。

我的错误在哪里?为什么会出现该错误及其原因?

import {
    LOGIN_REQUEST, LOGIN_SUCCESS, LOGIN_FAILURE, LOG_OUT,
    GETALL_REQUEST, GETALL_SUCCESS, GETALL_FAILURE
} from './types';
import axios from 'axios';

export function getAllUser() {
    return dispatch => {
        dispatch(request());
        axios.get('https://jsonplaceholder.typicode.com/users')
            .then(res => console.info(res.data))
            .then(
                users => dispatch(success(users)),
                error => dispatch(failure(error))
            )
    }
    function request() {
        return { type: GETALL_REQUEST }
    }
    function success(users) {
        return {
            type: GETALL_SUCCESS,
            payload: users
        }
    }
    function failure(error) {
        return {
            type: GETALL_FAILURE,
            error
        }
    }
}
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { getAllUser } from '../../actions/authenticationActions';

class Users extends Component {

    componentWillMount() {
        this.props.getAllUser()
    }
    render() {
        console.info(`users:`, this.props.users)
        const userList = this.props.users.map(user => (
            <tr key={user.id}>
                <td>{user.name}</td>
                <td>{user.username}</td>
                <td>{user.email}</td>
            </tr>
        ));
        if (!userList) {
            return (
                <div>
                    Not Found...
            </div>
            )
        }
        return (
            <div>
                <table className="table">
                    <thead>
                        <tr>
                            <th scope="col">Name</th>
                            <th scope="col">Username</th>
                            <th scope="col">Email</th>
                        </tr>
                    </thead>
                    <tbody>{userList}</tbody>
                </table>
            </div>
        );
    }
}

Users.propTypes = {
    getAllUser: PropTypes.func.isRequired,
};

const mapStateToProps = state => {
    console.info('state', state);
    return {
        users: state.users.items,
        isFetching: state.users.isFetching
    }
};

const mapDispatchToProps = dispatch => {
    return {
        getAllUser: users => dispatch(getAllUser(users))
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Users);
import { GETALL_REQUEST, GETALL_SUCCESS, GETALL_FAILURE } from '../actions/types';

const initialState = {
    items: [],
    item: {},
    isFetching: true
}

export default function (state = initialState, action) {
    switch (action.type) {
        case GETALL_REQUEST:
            return {
                ...state,
                isFetching: true,
            };
        case GETALL_SUCCESS:
            return {
                ...state,
                items: action.payload,
                isFetching: false
            };
        case GETALL_FAILURE:
            return {}
        default:
            return state
    }
}

3 个答案:

答案 0 :(得分:0)

我已将您的代码构建到沙箱中,并且您面临的问题仍在您的操作中。您不能在动作内部执行副作用。 Redux会抱怨:

enter image description here

要解决此问题,您有两个选择:

  1. 使用componentDidMount()如果需要从远程端点加载数据,这是实例化网络请求的好地方。
    componentDidMount() {
        axios
            .get('https://jsonplaceholder.typicode.com/users')
            .then(response => {
                console.log(response.data);
                // this.setState({ response.data });
            })
            .catch(error => {
                console.log(error);
            });
    }
  1. 使用中间件(例如redux-saga,redux-thunk)来处理您的副作用,即您的get请求。

答案 1 :(得分:0)

console.info返回未定义,因此您不将数组传递给成功处理程序,而是未定义

使用

.then(res => res.data)

.then(res => {console.info(res.data); return res.data;})

请参见以下示例中的区别:

var promise = new Promise(function(resolve){
  resolve([1,2,3]);
});

promise.then(res=>{console.info("1 step",res); return res}) //return array
       .then(res=>console.info("2 step", res)) //only log
       .then(res=>console.info("3 step", res)) //ups... res is undefined

答案 2 :(得分:0)

尝试:

axios.get('https://jsonplaceholder.typicode.com/users')
    .then(res => dispatch(success(res)))
    .catch(err => dispatch(failure(error)))

我认为响应中没有数据键!这就是为什么您会收到该错误!