reactjs - Using for each to create react components within another component
问题描述
Suppose I have some data for car listings, I want to represent each of these listing object using a react component defined as "VehicleListing". And I want to render each of the listings inside another react component called "VehicleTypes".
Below I am trying to use the forEach method to accomplish that but for some reason, the forEach method won't render anything onto the DOM. Does anyone know why? Also, is potentially there a better way of accomplishing this same task?
Thank you!
let Cars = [
{ year: 2013, model: "A", price: "$32000" },
{ year: 2011, model: "B", price: "$4400" },
{ year: 2016, model: "B", price: "$15500" },
];
function VehicleListing(props) {
return (
<ul>
<table>
<tr>
<th>Year</th>
<th>Model</th>
<th>Price</th>
<th>Buy</th>
</tr>
<tr>
<td>{props.data.year}</td>
<td>{props.data.model}</td>
<td>{props.data.price}</td>
<td>
<button>Buy Now</button>
</td>
</tr>
</table>
</ul>
);
}
function VehicleTypes(props) {
return (
<div>
<h2>{props.vehicleType}</h2>
{Cars.forEach((listing) => {
return <VehicleListing data={listing} />;
})}
</div>
);
}
function ReactTransportationApp(props) {
return (
<div>
<PageTitle />
<ChooseOptions />
<VehicleTypes vehicleType="Cars" />
</div>
);
}
解决方案
Array.forEach
only returns undefined
so it's no use here. From MDN:
forEach() executes the callback function once for each array element; unlike map() or reduce() it always returns the value undefined and is not chainable. The typical use case is to execute side effects at the end of a chain.
You need to use Array.map
:
function VehicleTypes(props) {
return (
<div>
<h2>{props.vehicleType}</h2>
{Cars.map((listing) => {
return <VehicleListing data={listing} />;
})}
</div>
);
}
... and you don't even need to explicit return statement if you remove the braces, so it can be written slightly more tersely:
function VehicleTypes(props) {
return (
<div>
<h2>{props.vehicleType}</h2>
{Cars.map(listing =>
<VehicleListing data={listing} />;
)}
</div>
);
}