简体   繁体   中英

Count Incrementer not setting state in react-hooks

I've a list of Meal components, which I render inside a MealList component. For each meal I want to pass a count value. This is my code.

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;

This breaks the code, how do setState correctly ?

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

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

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

You need to add on change or similar event to update count. This is the sample code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM