我有一个在MealList组件中呈现的Meal组件列表。对于每顿饭,我想传递一个计数值。这是我的代码。
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?
发布于 2019-12-30 09:42:49
如果你使用count props作为索引,那么你不需要use state,你可以为此传递数组索引:
{props.meals.map((meal, index) => (<Meal count={index +1} meal={meal}/>))}发布于 2019-12-30 09:30:20
计数{ () => setCount(count+1) }计数{count=}
您需要添加更改或类似事件来更新计数。这是示例代码
https://stackoverflow.com/questions/59524743
复制相似问题