【发布时间】:2021-12-30 10:29:58
【问题描述】:
我有一个 .map 函数显示从 api 中提取的数据,我想在数据中添加一个字段并使其与相关数据相匹配。
例如,我从一个包含数量的 api 中提取成分,我想添加一个输入字段,允许我添加一个乘数,以后可以用来乘以成分。
这里是 .map 函数:
<div className="mt-4 border-t border-b border-gray-200 divide-y divide-gray-200">
{data.ingredients.map((ingredient) => (
<div
key={ingredient.id}
className="relative flex items-start py-4"
>
<div className="ml-4 flex items-center h-5">
<input
onChange={selectIngredient(ingredient.id)}
value={selectedIngredients.indexOf(ingredient.id === -1)}
type="checkbox"
className="focus:ring-purple-500 h-4 w-4 text-purple-600 border-gray-300 rounded"
/>
</div>
<div className="ml-3 text-sm">
<label
className="font-medium text-gray-700 select-none"
>
{ingredient.name}
</label>
</div>
<div className="ml-3 text-sm">
// Here I am using useState to set a multiplier, but it sets the same vale for all data in the .map list.
<input
value={multiplier}
onChange={(e) => setMultiplier(e.target.value)}
type="number"
className="flex-1 focus:ring-purple-500 focus:border-purple-500 block w-full min-w-0 rounded-md sm:text-sm border-gray-300"
/>
</div>
</div>
))}
</div>
成分对象如下所示:
ingredient: {
id: 1,
name: sugar,
quantity: 100,
quantityUnit: grams,
}
有没有办法设置与相关映射数据相关联的状态?
【问题讨论】:
-
我建议您将 API 中的所有数据存储到一个状态中,并为您获得的每个
ingredient添加一个multiplier属性。然后使用该数据集来呈现您的字段。 -
谢谢@EmielZuurbier,我如何将单个的乘数添加到状态?
标签: javascript arrays reactjs