【问题标题】:TypeError: Cannot read property 'map' of undefined iwith react-reduxTypeError:无法使用 react-redux 读取未定义 i 的属性“地图”
【发布时间】:2019-12-19 08:06:39
【问题描述】:

我遵循 react-redux 教程并尝试显示帖子。我从https://jsonplaceholder.typicode.com/posts 获取帖子数据。它返回这样的响应:

import React from 'react';
import { connect } from 'react-redux';
import { fetchPost } from '../actions'

class PostList extends React.Component{
    componentDidMount(){
        this.props.fetchPost();
    }
    renderList(){
        return this.props.post.map(pos => {
            return (
                <div className="item" key={pos.id}>
                    <p>{pos.title}</p>
                </div>
            );
        });
    }
    render(){
        return(<div className="ui relaxed divided list"> {this.renderList()} </div>);
    }
}
const mapStateToProps = (state) =>{
    return { post:state.post}
}
export default connect(mapStateToProps , { fetchPost })(PostList);

这是我的动作创建者

import JsonPlaceHolder from '../apis/JsonPlaceHolder'
export const fetchPost = () => {
    return async (dispatch) => {
        const response = await JsonPlaceHolder.get('/posts');
        dispatch({
            type: 'FETCH_POST',
            payload:response
        });
    }
};

这是我的减速器

export default (state=[],action) => {
    switch(action.type){
        case "FETCH_POST":
            return action.payload;
        default:
            return state;
    }
};

这是我的 ../apis/JsonPlaceHolder 文件

import axios from 'axios';

export default axios.create({
    baseURL:"https://jsonplaceholder.typicode.com/"
});

但我收到这样的错误

TypeError: this.props.post.map 不是函数

【问题讨论】:

  • 请发../apis/JsonPlaceHolder文件

标签: reactjs react-redux


【解决方案1】:

我认为,您应该在映射之前检查您是否有this.props.post,因为请求需要一些时间,在此过程中您可能会从this.props.post 收到undefined 值。

另外,如果你想映射this.props.post,那么你不仅应该作为有效载荷返回response,还应该返回response.data。否则,您将收到一个错误,即该对象没有方法 map

【讨论】:

    【解决方案2】:

    你必须从response中提取data

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

    【讨论】:

      【解决方案3】:

      您还可以从响应中提取数据

      const mapStateToProps = (state) =>{
          return { post:state.post.data}
      }
      

      【讨论】:

        猜你喜欢
        • 2019-03-19
        • 2019-10-29
        • 1970-01-01
        • 2020-07-23
        • 2019-02-08
        • 1970-01-01
        • 2017-02-21
        • 2017-03-26
        • 2021-09-09
        相关资源
        最近更新 更多