【发布时间】:2021-10-26 19:04:24
【问题描述】:
我有一个奇怪的问题。在我的 React 项目中,我有一个包含信息的 useState([]) 变量。在网站上,我有一个“添加”按钮,可以将新的价格对象添加到数组中。
然后通过地图直观地显示在网站上。每个部分(数组中的对象)都有一个删除按钮。当我删除一个部分时,它只会删除新添加的对象。但是,当我 console.log() 更新的值时,它已经删除了正确的对象。
所以,总结一下。在存储的值中,它删除正确,但它不会在视觉上正确显示。谁能帮忙?
代码如下:
我的 .map() 代码,底部是删除部分的代码:
{courseData.prices?.map((price, i) => {
return (
<div
className='flex flex-wrap bg-white mb-4 p-2 rounded-md shadow-md'
key={i}>
<Input
label='Navn'
value={price.name}
width='1/2'
white
isRequired
handleChange={(e) => updatePrice(e, i, 'name')}
/>
<Input
label='Beskrivelse'
value={price.description}
width='1/2'
white
isRequired
handleChange={(e) => updatePrice(e, i, 'description')}
/>
<Input
label='Pris'
type='number'
width='1/2'
value={price.price}
white
isRequired
handleChange={(e) => updatePrice(e, i, 'price')}
/>
<Input
label='Gyldighet (dager)'
type='number'
width='1/2'
value={price.days}
white
isRequired
handleChange={(e) => updatePrice(e, i, 'days')}
/>
<button
type='button'
onClick={() => {
setCourseData((courseData) => {
return {
...courseData,
prices: courseData.prices.filter((item) => item !== price),
}
})
}}
className='flex items-center min-w-max rounded-md px-2 py-1 m-1 bg-white-light shadow-md font-semibold text-gray-500 active:shadow-none'>
<XIcon className='h-4 w-4' />
<p className='font-medium ml-1'>Fjern</p>
</button>
</div>
)
})}
删除中间后的存储数据(你看存储的数据和可视化组件的名字不一样):
【问题讨论】:
-
我认为这里的问题与 key 有关。为地图内呈现的 div 提供唯一键而不是索引。
key={price.courseID} -
在您分享的屏幕截图中,为什么索引 0 中的对象与索引 1 中的对象不同?
标签: javascript arrays reactjs react-hooks use-state