首页 > 解决方案 > 计数增量器未在反应挂钩中设置状态

问题描述

我有一个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正确执行?

标签: javascriptreactjsreact-hooks

解决方案


如果你使用 count props 作为索引,那么你就不需要使用 state,你可以为此目的传递数组索引:

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

推荐阅读