在 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>
);
}
}
你可以用根元素包装它,如div
, React ver 15 渲染函数仅支持返回一个元素。
render() {
<div>{this.state.myData.map((item) =>
<div>
<h3>{item.title}</h3>
<p>{item.description}</p>
</div>
)}</div>
}
}
像这样更改,当您使用map
时key
应该使用索引的属性
makeUI() {
if(!this.state.myData.length)
return
return this.state.myData.map((item, index) => {
return (
<div key={index}>
<h3>{item.title}</h3>
<p>{item.description}</p>
</div>
)
})
}
render() {
return (<div>
{ this.makeUI() }
</div>
)
}
我认为您在 renderList -> .map 中缺少返回
这应该有效。
renderList() {
return this.state.myData.map((item) => {
return (
<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>
);
}
}