首页 > 解决方案 > 无法映射在反应 js 中收到的响应

问题描述

我正在编写一个基于 react redux 的 Web 应用程序,但我无法绘制出从 redux 商店获得的响应。我总是得到一个错误,说 map 不是一个函数。我可以通过控制台查看数据通过记录它,但它在下一秒崩溃我使用地图功能来检索它们。这是响应,我无法映射任何数据。

JSON响应

这是我为获取块计数响应而创建的代码。

import React, { useEffect } from 'react';
import { connect } from 'react-redux';
import { fetchPost } from '../../Redux/Post-Redux/PostActionMethods';
import './PostBody.css';


function PostBody({postdata}) {

    console.log(postdata);

    var blockcount = postdata.postchapter.map((key)=>{
        return key.blockcount
    })
    
    console.log(blockcount);
    
    return postdata.isLoading ? (<h2>Loading...</h2>) :
            postdata.error ? (<h2>{postdata.error}</h2>) :
            (
                <div>
                    <p>Some texts</p>
                </div>
            )
    
}

const mapStatetoProps = (state) =>{
    return{
        postdata:state.PostChapter
    }
}


export default connect(mapStatetoProps)(PostBody);

当我运行这个我得到错误:TypeError: postdata.postchapter.map is not a function

我如何纠正这一点并获得内容响应,而我无法检索块数本身?

这是我需要正确检索的内容响应。

在此处输入图像描述

标签: javascriptreactjsreact-reduxreact-router

解决方案


map()Array的方法,但是postdata.postchapterObject

你不能只用

var blockcount = postdata.postchapter.blockCount;

代替

var blockcount = postdata.postchapter.map((key)=>{
    return key.blockcount
})

- 编辑 -

如果需要渲染postdata.postchapter.content

text财产例如,

然后:

function PostBody({postdata}) {

    console.log(postdata);

    var content = postdata.postchapter.content?.map((item, index)=>{
        return <p key={index}>{item.text}</p>
    })
    
    return postdata.isLoading ? (<h2>Loading...</h2>) :
            postdata.error ? (<h2>{postdata.error}</h2>) :
            (
                <div>
                    {content}
                </div>
            )
    
}

这是有关渲染列表的反应文档


推荐阅读