gpt4 book ai didi

javascript - 您可能返回了未定义的数组或其他一些无效的对象渲染状态数据

转载 作者:行者123 更新时间:2023-12-03 03:34:59 26 4
gpt4 key购买 nike

在 React 中迭代列表和打印元素时遇到问题。

react 代码是:

import React from 'react';
import ReactDOM from 'react-dom';

class NewComponent extends React.Component {
constructor(props){
super(props);
this.state = {myData: []}
}

componentWillMount(){
let data = document.getElementById('demo').innerHTML;
data = JSON.parse(data);
this.setState({myData: data});
}

render() {
return this.state.myData.map((item) => {
return (
<div>
<h3>{item.title}</h3>
<p>{item.description}</p>
</div>
);
});
}
}


ReactDOM.render(
<NewComponent />,
document.getElementById('demo')
)

我收到一个错误:

bundle.js:830 Uncaught Error: NewComponent.render(): A valid React element 
(or null) must be returned. You may have returned undefined, an array or
some other invalid object.

我很确定渲染函数中的返回存在一些问题但不确定问题是什么。

编辑

我进行了以下编辑,错误不再存在,但没有任何渲染。

renderList() {
console.log("Running");
return this.state.myData.map((item) => {
<div>
<h3>{item.title}</h3>
<p>{item.description}</p>
</div>
});
}

render() {
console.log(this.state.myData);
if(this.state.myData.length)
return <div>{this.renderList()}</div>
else
return <div>Loading...</div>
}

在 Chrome 控制台中我得到:

(2) [{…}, {…}]
0:{_id: {…}, description: "hello", title: "sankit"}
1:{_id: {…}, description: "lets add some thing new", title: "hi"}
length:2
_proto_:Array(0)

Running

最佳答案

你可以做的是从渲染方法中提取你的js代码在一个单独的方法中,如下所示:

renderList() {
return this.state.myData.map((item) => {
<div>
<h3>{item.title}</h3>
<p>{item.description}</p>
</div>
})
}

然后在你的渲染方法中:

render() {
if(this.state.myData.length){
return (
<div>{this.renderList()}</div>
);
}
else
{
return (
<div>Loading...</div>
);
}
}

关于javascript - 您可能返回了未定义的数组或其他一些无效的对象渲染状态数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45908668/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com