我想循环一个数组并从中创建列表项。在控制台中,它显示错误被抛出,因为我的数组没有键但只有值。那么读出数组的正确操作是什么?
*// this.props.items = ["cars","streets","houses"];*Wrong. You can't update props
var TodoList = React.createClass({
render: function() {
var createItem = function(item) {
return <li>{item}</li>;
};
return <ul>{this.props.items.map(createItem)}</ul>;
}
});
答案 0 :(得分:9)
尝试这种方式:
this.filterOptions =['Monthly','Weekly','Daily'];
<ul>
{ this.filterOptions.map((filterItem) => {
return (
<li key={filterItem}>
<span>{filterItem}</span>
</li>
);
})
}
</ul>
编辑1:如果数组中有重复值,
<ul>
{ this.filterOptions.map((filterItem,index) => {
return (
<li key={index}>//key must be uniq
<span>{filterItem}</span>
</li>
);
})
}
</ul>
答案 1 :(得分:1)
只是为了澄清,因为我看到你使用:
var TodoList = React.createClass({
而不是
class TodoList extends React.Component {
以及上述评论中关闭括号的问题: “是否缺少右括号((filterItem,index)”“
我假设你没有使用es6语法,所以我想指出
{ this.filterOptions.map(function(filterItem, index) {
return (
<li key={index}>
<span>{filterItem}</span>
</li>
)
}, this)
}
等于
{ this.filterOptions.map((filterItem,index) => {
return (
<li key={index}>
<span>{filterItem}</span>
</li>
);
})
}