我正在学习 React,想使用 map() 函数。这是我的代码:
class App extends Component {
state = { car:[
{carTitle:'Toyota'},
{carTitle: 'Honda'},
{cartitle: 'Chevrolet'}
] };
render() {
return ( <div>
{this.state.car.map((item, index)=>
<h1>{item.carTitle}</h1>
)}
</div> );
}
}
问题是为什么我使用
{this.state.car.map((item, index)=>
<h1>{item[index].carTitle}</h1>
我收到一个错误。由于我有对象数组,我认为使用 {item[index].carTitle}
是合乎逻辑的。但如果我使用 <h1>{item.carTitle}</h1>
,一切正常。为什么?我是不是误会了什么?
最佳答案
当您使用.map()
时您需要传递一个函数作为回调,就像您已经传递的函数一样: .map( (item, index) => ... )
该回调函数的第一个参数 item
,是数组中当前正在处理的元素。 index
是当前位置。
item
已经返回数组每个位置的内容,在本例中是您在 car
中定义的每个对象。 .
所以,你的第二个例子,item[index].carTitle
,是不正确的,因为您试图访问每个对象内不存在的数组位置。
此外,每次您使用 .map()
在ReactJS应用程序中,您需要指定key
到您在此函数内返回的元素,在本例中: <h1 key={index}>{{car.carTitle}}</h1>
.
黄金提示:为了使您的代码更清晰并避免混淆,您应该重命名 car
至cars
,因为它是汽车列表,而不是使用 item
你应该使用car
。它将使您的代码更加清晰,并且与使用通用名称相比,任何阅读您的代码的人都可以更容易地理解它。所以它看起来像这样:
cars: [
{carTitle:'Toyota'},
{carTitle: 'Honda'},
{cartitle: 'Chevrolet'}
]
和:
{this.state.cars.map( (car, index) => {
<h1 hey={index}>{{car.carTitle}}</h1>
})}
进一步阅读:
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
- https://reactjs.org/docs/lists-and-keys.html
- 《干净的代码》,罗伯特·塞西尔·马丁 (Robert Cecil Martin) 所著书籍
关于javascript - 与 JavaScript 中的 map() 混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60345410/