我一直试图在React中迭代一组数据。它在控制台中没有给我任何错误,但它说
[HMR]等待来自WDS的更新信号...... [WDS]已启用热模块更换。
Index.js
import React, {Component} from 'react';
import {render} from 'react-dom';
var items = [
{ name: 'Matthew', link: 'https://bible.com/1/mat.1' },
{ name: 'Mark', link: 'https://bible.com/1/mrk.1' },
{ name: 'Luke', link: 'https://bible.com/1/luk.1' },
{ name: 'John', link: 'https://bible.com/1/jhn.1' }
];
class Home extends Component {
constructor(props) {
super(props);
this.state = {
items: []
};
};
render(){
var listItems = this.state.items.map(function(item) {
return (
<li key={item.name}>
<a className='button' href={item.link}>{item.name}</a>
</li>
);
});
return (
<ul>
{listItems}
</ul>
);
}
}
render(<Home />,document.getElementById('contain'));
我不明白如何解决它。任何形式的帮助将不胜感激。
答案 0 :(得分:1)
由于状态items
为empty
,您无法获得任何输出,您需要将状态初始化为items
或迭代变量items
< / p>
var items = [
{ name: 'Matthew', link: 'https://bible.com/1/mat.1' },
{ name: 'Mark', link: 'https://bible.com/1/mrk.1' },
{ name: 'Luke', link: 'https://bible.com/1/luk.1' },
{ name: 'John', link: 'https://bible.com/1/jhn.1' }
];
class Home extends Component {
constructor(props) {
super(props);
this.state = {
items: items
};
};
render(){
var listItems = this.state.items.map(function(item) {
return (
<li key={item.name}>
<a className='button' href={item.link}>{item.name}</a>
</li>
);
});
return (
<ul>
{listItems}
</ul>
);
}
}
render(<Home />,document.getElementById('contain'));
答案 1 :(得分:0)
您的状态为空。你试图通过空状态map
。
您应该按如下方式初始化状态:
constructor(props) {
super(props);
this.state = {
items: items
};
};
或者在生命周期方法中如下:
componentWillMount(){
this.setState({items: items})
}
或者您应该map
到items
,如下所示:
var listItems = items.map(function(item) {
return (
<li key={item.name}>
<a className='button' href={item.link}>{item.name}</a>
</li>
);
});
您的代码应如下所示(使用生命周期方法初始化状态):
import React, {Component} from 'react';
import {render} from 'react-dom';
var items = [
{ name: 'Matthew', link: 'https://bible.com/1/mat.1' },
{ name: 'Mark', link: 'https://bible.com/1/mrk.1' },
{ name: 'Luke', link: 'https://bible.com/1/luk.1' },
{ name: 'John', link: 'https://bible.com/1/jhn.1' }
];
class Home extends Component {
constructor(props) {
super(props);
this.state = {
items: []
};
};
componentWillMount(){
this.setState({items: items})
}
render(){
var listItems = this.state.items.map(function(item) {
return (
<li key={item.name}>
<a className='button' href={item.link}>{item.name}</a>
</li>
);
});
return (
<ul>
{listItems}
</ul>
);
}
}
render(<Home />,document.getElementById('contain'));