计数增量器未在反应钩中设置状态

时间:2019-12-30 01:22:02

标签: javascript reactjs react-hooks

我有一个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

2 个答案:

答案 0 :(得分:1)

如果将count道具用作索引,则不需要使用状态,则可以为此目的传递数组索引:

{props.meals.map((meal, index) => (<Meal count={index +1} meal={meal}/>))}

答案 1 :(得分:-1)

onChange = {()=> setCount(count + 1)} count = {count}

您需要添加更改或类似事件以更新计数。这是示例代码