尝试在 React 中创建一个 li 但失败了。错误在 map() 附近,我得到错误 i is not defined,为什么?
const TodoItems = React.creatClass({
getInitialState() {
return {
items : [
{id:1,name:"Gym"},
{id:2,name:"Jump"},
{id:3,name:"Racing"}
]
}
},
renderItem(){
return(
<ul>
this.state.items.map(item,i =>
<li key={i}>item.name</li>
)
</ul>
)
},
render(){
return (
<renderItem />
)
}
})
最佳答案
当箭头函数有多个参数时,您需要在它们周围放置 ()
。所以:
this.state.items.map((item,i) =>
// ------------------^------^
<li key={i}>item.name</li>
)
您的原始代码以 item
作为第一个参数调用 map
,并以单个参数 (i
) 作为第二个参数调用箭头函数争论。
您还需要将 item.name
放入 {}
并将对 map
的调用放入 {}
:
renderItem(){
return(
<ul>
{this.state.items.map((item,i) =>
<li key={i}>{item.name}</li>
)}
</ul>
)
然后就可以了:
const { Component } = React;
const { render } = ReactDOM;
const TodoItems = React.createClass({
getInitialState() {
return {
items : [
{id:1,name:"Gym"},
{id:2,name:"Jump"},
{id:3,name:"Racing"}
]
}
},
renderItem(){
return(
<ul>
{this.state.items.map((item,i) =>
<li key={i}>{item.name}</li>
)}
</ul>
)
},
render(){
return this.renderItem();
}
});
render(<TodoItems /> , document.getElementById('items'));
<div id="items"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
当我使用 Babel's REPL to compile the JSX 时,我清楚了这一点并意识到我看到的是 "this.state.map((item,i) =>"
string。
关于javascript - i 没有在 ES6 中使用 map() 定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39815186/