reactjs - 类型错误 : Cannot read property 'map' of undefined iwith react-redux

标签 reactjs react-redux

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

enter image description here

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);

这是我的 Action 创建器

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

这是我的 reducer

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 is not a function

最佳答案

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

另外,如果您想映射 this.props.post,那么您应该返回的不仅仅是 response,而是 response.data >。否则,您将收到一个错误,指出该对象没有 map 方法。

关于reactjs - 类型错误 : Cannot read property 'map' of undefined iwith react-redux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59405552/

相关文章:

javascript - react native 自定义组件

javascript - "Cannot read property ' setState ' of undefined"即使它是绑定(bind)的

reactjs - 如何浅测试使用 redux hooks 的非 redux 连接组件

reactjs - 如何将参数传递给从自定义 Hook 转换的函数?

javascript - 如何在拼接层中重用微前端定义的 Web 组件?

javascript - react 意外 token : operator (<)

javascript - 未捕获的类型错误 : Cannot read property 'get' of null in map function

javascript - 了解 React-Redux 和 mapStateToProps()

react-native - 如何将 Store 共享到 TabNavigator

javascript - React 中的对象