我有一个MealList组件,其中列出了一组Meal组件。
const MealList = (props) => {
console.log(props.meals);// [Array(3)]
return (
<div style={{width: '70%'}}>
<h3 style={{color: 'grey', fontSize: '1.4em', fontWeight: '700', marginBottom: '1em'}}><FontAwesomeIcon
icon={faPlusCircle} style={{color: '#007bff', marginRight: '0.5em'}}/> ADD MEAL</h3>
<Table striped bordered hover>
<thead>
<tr>
<th>#</th>
<th>Meal</th>
<th>Calories</th>
<th>Time</th>
<th>Date</th>
<th>Update</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
{props.meals.map(meal => <Meal label={meal.label} calories={meal.calories} time={meal.time}
date={meal.date}/>)}
</tbody>
</Table>
</div>
)
};
export default MealList;
这是控制台上阵列的结构。
[Array(3)]
0: Array(3)
0: {id: 8, label: "Breakfast", calories: 311, time: "20:10:00", date: "2019-12-29", …}
1: {id: 9, label: "Lunch", calories: 721, time: "20:10:00", date: "2019-12-29", …}
2: {id: 10, label: "Dinner", calories: 663, time: "20:10:00", date: "2019-12-29", …}
length: 3
虽然props值未定义,但在Meal组件内部。
const Meal = (props) => {
console.log(props.label, props.calories, props.time, props.data);//undefined ....
return (<tr>
<td>1</td>
<td>{props.label}</td>
<td>{props.calories}</td>
<td>{props.time}</td>
<td>{props.date}</td>
<td><FontAwesomeIcon icon={faUserEdit}/></td>
<td><FontAwesomeIcon icon={faMinusCircle}/></td>
</tr>);
};
export default Meal;
我在这里做什么错了?
答案 0 :(得分:1)
根据
[Array(3)]
您的props.meals
不是对象数组,而是对象数组的数组(带有单个元素)。
因此,虽然可以使用quickfix
{props.meals[0].map(meal =>
更好地检查为什么它以不同的结构出现,而不是您期望的
答案 1 :(得分:1)
我建议以下内容: