我有一个Meal
组件的列表,我在MealList
组件中渲染这些组件。对于每顿饭,我想传递一个计数值。这是我的代码。
const MealList = (props) => {
const [count, setCount] = useState(0);
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 count={setCount(count + 1)} meal={meal}/>))}
</tbody>
</Table>
</div>
)
};
export default MealList;
这破坏了代码,如何正确setState
?
如果你使用 count props 作为索引,那么你不需要 use state,你可以为此目的传递数组索引:
{props.meals.map((meal, index) => (<Meal count={index +1} meal={meal}/>))}
onChange={ ((=> setCount(count+1( } count={count}
您需要添加更改或类似事件来更新计数。这是示例代码