ReactJS:TypeError:this.state.data.map不是函数

ReactJS:TypeError:this.state.data.map不是函数,reactjs,react-grid-layout,Reactjs,React Grid Layout,-谁能帮我一下吗。我在这个问题的标题中发现了一个错误。我想把JSON数据放在react网格布局组件中。可以在()上找到此库 import React,{Component}来自'React'; 从“react dom”导入react dom; 从“./Employee”导入员工; 导入“/react grid layout/css/styles.css”; 导入“/react resizeable/css/styles.css” var ReactGridLayout=require('reac

-谁能帮我一下吗。我在这个问题的标题中发现了一个错误。我想把JSON数据放在react网格布局组件中。可以在()上找到此库

import React,{Component}来自'React';
从“react dom”导入react dom;
从“./Employee”导入员工;
导入“/react grid layout/css/styles.css”;
导入“/react resizeable/css/styles.css”
var ReactGridLayout=require('react-grid-layout');
var数据=[];
类MyFirstGrid扩展了React.Component{
构造函数(){
超级();
此.state={
数据:[]
};
}
componentDidMount(){
取回(“http://localhost:8080/TrainingWebMvcSpring2/roottypes/listAll.do")
。然后((响应)=>{
返回response.json()})
。然后((json)=>{
this.setState({data:json});
});
}
渲染(){
控制台日志(数据);
返回(
{this.state.data.map(函数(项,键){
返回(
{item}
{item}
{item}
)
})}
)
}
}
导出默认MyFirstGrid;
ReactJS:TypeError:this.state.data.map不是函数?

在阵列上可用

在fetch API调用之后

this.setState({data: json});
json
作为对象而不是转换数据的数组返回 对一个物体

将此更改为:

this.setState({data: [...json]});

您应该检查fetch调用是否成功。在承诺链的末尾添加一个
.catch()
是不够的(无论如何,您应该这样做),还必须检查成功的调用是否返回了OK响应,而不是404响应。比如说:

class MyFirstGrid extends React.Component {
    constructor() {
        this.state = {
            data: []
        }
    }

    componentDidMount(){
        fetch('http://localhost:8080/JiwayTrainingWebMvcSpring2/roottypes/listAll.do')
            .then( (response) => {
                if (response.ok) {
                    return response.json()
                } else {
                    throw new Error(`Fetch failed with code ${response.code}`)
                }
            })
            .then(json => {
                this.setState({data: json})
            })
            .catch(err => { console.log(`Something failed: ${err.message}`) };
    }

    render () {
        console.log(this.state.data);
        return (
            <ReactGridLayout className="layout" cols={12} rowHeight={30} width={1200}>
                {this.state.data.map(function(item, key){
                    return(
                        <div>
                        <div key="a" data-grid={{x: 0, y: 0, w: 1, h: 2, static: true}}> {item}</div>
                        <div key="b" data-grid={{x: 1, y: 0, w: 3, h: 2, minW: 2, maxW: 4}}> {item} </div>
                        <div key="c" data-grid={{x: 4, y: 0, w: 1, h: 2}}> {item} </div>
                        </div>
                    )
                })}
            </ReactGridLayout>
        )
    }
}

export default MyFirstGrid
类MyFirstGrid扩展了React.Component{ 构造函数(){ 此.state={ 数据:[] } } componentDidMount(){ 取('http://localhost:8080/JiwayTrainingWebMvcSpring2/roottypes/listAll.do') 。然后((响应)=>{ if(response.ok){ 返回response.json() }否则{ 抛出新错误(`Fetch失败,代码为${response.code}`) } }) 。然后(json=>{ this.setState({data:json}) }) .catch(err=>{console.log(`Something failed:${err.message}`)}; } 渲染(){ console.log(this.state.data); 返回( {this.state.data.map(函数(项,键){ 返回( {item} {item} {item} ) })} ) } } 导出默认MyFirstGrid
var data=[]
是一个全局空数组。我看不到您将其分配给任何其他对象,因此它将始终是一个空数组。因此
控制台.log(data)
[]
。请不要使用它

response.json()
json.parse(response.text())
相同,后者返回一个对象或一个对象数组。在您的例子中,由于没有
map
函数,我猜它返回一个对象

将对象转换为数组的最简单方法是使用
object.keys()
函数

const keys = Object.keys(json); // eg: json = {a: 1, b: 2}
const data = keys.map(key => json[key]); // eg: data = [1, 2]
this.setState({ data: data });
由于您没有告诉我们json响应的结构,因此很难为您的问题提供具体的答案

以下是如何测试响应是否为对象数组:

if (json.length) { /* array */ } 
eles { /* object will return undefined, which is false */ }
注: 刚刚看到你的评论。
this.setState({data:json.array})
应该可以

  • 代码中的另一个问题是
    constructor(props){super(props);}
    类中缺少
    props
这应该让你开始,不要忘了关键,当使用地图功能

class MyFirstGrid extends React.Component {
  state = { data: [] };

  async componentDidMount() {
    try {
      const response = await fetch("http://localhost:8080/TrainingWebMvcSpring2/roottypes/listAll.do");
      const data = response.json().array;
      console.log(data, data.length);
      this.setState({
        data: data,
      });
    } catch (err) {
      console.error(err);
    } 
  }

  render() {
    const dataGrid = this.state.data.map((item, index) => (
      <div key={index}>
        <div key="a" data-grid={{x: 0, y: 0, w: 1, h: 2, static: true}}> {item}</div>
        <div key="b" data-grid={{x: 1, y: 0, w: 3, h: 2, minW: 2, maxW: 4}}> {item} </div>
        <div key="c" data-grid={{x: 4, y: 0, w: 1, h: 2}}> {item} </div>
      </div>
    ));

    return(
      <ReactGridLayout className="layout" cols={12} rowHeight={30} width={1200}>
        {dataGrid}
      </ReactGridLayout>
    );
  }
}
类MyFirstGrid扩展了React.Component{ 状态={data:[]}; 异步组件didmount(){ 试一试{ const response=等待获取(“http://localhost:8080/TrainingWebMvcSpring2/roottypes/listAll.do"); const data=response.json().array; console.log(数据、数据、长度); 这是我的国家({ 数据:数据, }); }捕捉(错误){ 控制台错误(err); } } render(){ const dataGrid=this.state.data.map((项,索引)=>( {item} {item} {item} )); 返回( {dataGrid} ); } }
因为您的JSON结构如下:

{
    array: [{},{},{}]
}

因此,通过这种方式设置state可以解决您的问题:
this.setState({data:json.array});

当您在初始加载或获取API后出错时?您可以显示json的结构吗?请不要破坏您的帖子。一旦您发布了一个问题,它就属于堆栈溢出社区(根据SA CC许可证)。如果您想解除此帖子与您的帐户的关联,请查看如何在不使用呈现方法中的this.state的情况下访问状态?我不知道您为什么要这样做,但您可以将获取的数据分配给任何其他变量,如
this.data
,然后在
render()中检索该变量
函数。只有在不更改状态的情况下,
render()
函数将不会被调用。但您没有这样做。您正在设置状态,并安慰甚至不存在的
数据。
现在我已成功获取,但获取了未定义的对象…您知道问题出在哪里吗?网格当然是空的…请检查更新的代码(我刚刚更改了控制台中记录的变量)然后看看里面有什么。这有点帮助
{
    array: [{},{},{}]
}