javascript - 计数增量器未在反应挂钩中设置状态
问题描述
我有一个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 作为索引,那么你就不需要使用 state,你可以为此目的传递数组索引:
{props.meals.map((meal, index) => (<Meal count={index +1} meal={meal}/>))}
推荐阅读
- javascript - 格式化 HTML 打印
- image - 打开图层:如何显示与中心有一定偏移的功能的 svg 图标
- scala - Scala中的嵌套与展平模式匹配
- python-3.x - Python:在连接两个十六进制字符串时保持尾随零
- php - 从图像 Base64 字符串、PHP 创建 SVG
- google-app-engine - 有哪些方法可以限制在特定版本的 App Engine 上部署?
- soap - 生成的 Soap 客户端在 Elixir Distillery Release 中不起作用
- sapui5 - ColumnListItem - 事件处理程序“按下”未触发
- css - 使用 stroke-dashoffset 的 SVG 动画在 IE 中不显示
- android - 如何修复致命异常:AsyncTask #1