You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React-Redux实践报错:TypeError: this.props.post.map is not a function

解决React-Redux中map is not a function错误

我来帮你搞定这个问题!你遇到的TypeError: this.props.post.map is not a function错误,核心原因是你在action creator里把axios返回的整个response对象当成了payload传给reducer,但实际上我们需要的是response里的data字段——也就是接口返回的文章数组。

问题根源

axios发起请求后,返回的response是一个包含元数据(状态码、请求头、配置等)的对象,而接口返回的文章数组实际存储在response.data属性中。你之前把整个response对象传给了reducer,导致state.post变成了一个对象,而对象没有map方法,自然就会报错。

修复步骤

只需要修改你的action creator代码,把payload从response改为response.data即可:

// 修改后的action creator
import JsonPlaceHolder from '../apis/JsonPlaceHolder'
export const fetchPost = () => {
  return async (dispatch) => {
    const response = await JsonPlaceHolder.get('/posts');
    // 重点:使用response.data作为payload,而不是整个response对象
    dispatch({ type: 'FETCH_POST', payload: response.data });
  };
};

额外优化(可选)

为了提升用户体验,你可以在组件中添加加载状态的判断,避免在数据还未请求完成时出现异常:

// 修改PostList组件的renderList方法
renderList(){
  // 如果posts数组为空,显示加载提示
  if (!this.props.post.length) {
    return <div>正在加载文章...</div>;
  }
  return this.props.post.map(pos => {
    return (
      <div className="item" key={pos.id}>
        <p>{pos.title}</p>
      </div>
    );
  });
}

这样修改后,你的组件就能正确遍历文章数组并渲染内容了!

内容的提问来源于stack exchange,提问作者Madushanka kahawa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 09:13:25