【问题标题】:Push elements into existing array in React Hooks将元素推送到 React Hooks 中的现有数组中
【发布时间】:2020-09-15 06:56:51
【问题描述】:

假设我有一个数组

const defaultList = [
  {
    "name":"John",
    "last_name":"doe"
  },
  {
    "name":"Alice",
    "last_name":"Smith"
  }
]

我想使用for循环添加新值online,所以最后它会是这样的

const defaultList = [
      {
        "name":"John",
        "last_name":"doe",
        "online":"yes"
      },
      {
        "name":"Alice",
        "last_name":"Smith",
         "online":"no"
      }
    ]

我正在使用 React Hooks 并且数组是以这种方式定义的,稍后我用上面的数据填充它:

const [defaultList, setDefaultList] = useState([]);

如果知道该怎么做,我将不胜感激?

谢谢!

【问题讨论】:

    标签: arrays reactjs react-hooks


    【解决方案1】:

    你可以使用.map

    const res = defaultList.map(el => ({ ...el, online: 'yes' })
    

    const defaultList = [
      {
        name: 'John',
        last_name: 'doe'
      },
      {
        name: 'Alice',
        last_name: 'Smith'
      }
    ]
    
    const res = defaultList.map(el => ({ ...el, online: 'yes' }))
    
    console.log(res)

    或者.forEachObject.assign()

    defaultList.forEach(el => {
      Object.assign(el, { online: 'yes' })
    })
    

    const defaultList = [
      {
        name: 'John',
        last_name: 'doe'
      },
      {
        name: 'Alice',
        last_name: 'Smith'
      }
    ]
    
    defaultList.forEach(el => {
      Object.assign(el, { online: 'yes' })
    })
    
    console.log(defaultList)

    ..相当于for..of循环

    for (const el of defaultList) {
      Object.assign(el, { online: 'yes' })
    }
    

    const defaultList = [
      {
        name: 'John',
        last_name: 'doe'
      },
      {
        name: 'Alice',
        last_name: 'Smith'
      }
    ]
    
    for (const el of defaultList) {
      Object.assign(el, { online: 'yes' })
    }
    
    console.log(defaultList)

    不同之处在于第一种方法创建了整个新数组,而其他方法是对原始数组进行变异

    【讨论】:

    • map 方法绝对是更好的选择 :)
    【解决方案2】:

    你不能有 2 个同名的两个变量 首先,通过以下方式设置默认状态:

    const [list, setList] = useState(defaultList)
    

    更换新列表后,调用setList

    setList(newDefaultList)
    

    使用list 代替defaultList 来满足您的需求

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-07
      • 1970-01-01
      • 1970-01-01
      • 2021-12-03
      相关资源
      最近更新 更多