TypeError:呈现用户评论列表时,无法读取未定义的属性“ map”

时间:2019-05-03 08:28:35

标签: reactjs redux react-redux axios redux-thunk

我正在尝试从伪造的api(json占位符)中获取帖子,但是却收到TypeError消息,提示无法读取未定义的属性“ map”

这是课程的组成部分

import React, { Component } from 'react'
import { connect } from 'react-redux'

import fetchPosts from '../actions/postListAction'

 class PostList extends Component {

componentDidMount() {
    this.props.fetchPosts();
}

  renderList() {
      return this.props.posts.map(post => {
          return (
          <div className="row" key={post.id}>
              <i class="fas fa-user align-left"></i>
              <div className="content">
                  <div className="description">
                      <p>{post.title}</p>
                      <p>{post.body}</p>
                  </div>
              </div>
          </div>
          );
      });
  }

  render() {
    return (
      <div>
        <h3>Posts</h3>
        <div className="post-list">
        {this.renderList()}
        </div>
      </div>
    )
  }
}

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

export default connect(mapStateToProps, { fetchPosts })(PostList)

这是动作创建者

import jsonPlaceholder from '../apis/jsonPlaceholder'

const fetchPosts = () => async dispatch => {
        const response = await jsonPlaceholder.get('/posts');
    dispatch({ type: 'FETCH_POSTS', payload: response })
}

export default fetchPosts

这是减速器

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

使用axios的jsonplaceholder中的API

import axios from 'axios';

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

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

您有错字。

在mapStateToProp中将

匹配(POST)到state.posts 但是在您的地图方法中,您是在this.props。(POSTS)中说 这些应该是相同的。以太坊帖子 您必须检查rootReducer并向您的组件传递正确的密钥