【问题标题】:React isn't updating the visual data, but useState has the right valueReact 没有更新视觉数据,但 useState 具有正确的值
【发布时间】: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>
  )
})}

删除前的视觉组件图片:

删除数字2(中间)之后的视觉组件的图片:

删除中间后的存储数据(你看存储的数据和可视化组件的名字不一样):

【问题讨论】:

  • 我认为这里的问题与 key 有关。为地图内呈现的 div 提供唯一键而不是索引。 key={price.courseID}
  • 在您分享的屏幕截图中,为什么索引 0 中的对象与索引 1 中的对象不同?

标签: javascript arrays reactjs react-hooks use-state


【解决方案1】:

我尝试重新创建问题here,但一切正常。

我猜是有一些不良数据导致了这个问题,但我也同意 cmets 中的建议:比较对象的属性而不是比较对象本身。

使用这个:

setCourseData(courseData => {
  return {
    ...courseData,
    prices: courseData.prices.filter(item => item.id !== price.id)
  };

而不是这个:

setCourseData(courseData => {
  return {
    ...courseData,
    prices: courseData.prices.filter(item => item !== price)
  };

如果这不能解决问题,您能否分享更多数据?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-03
    • 1970-01-01
    • 2021-01-09
    • 2012-06-15
    • 2021-08-05
    • 1970-01-01
    • 2020-12-28
    • 1970-01-01
    相关资源
    最近更新 更多