Apollo 不变性错误 - 无法分配给对象的只读属性“状态”

问题描述 投票:0回答:1

我正在尝试解决以下代码引发的错误:

const [releaseHold] = useMutation(UPDATE_UNIT_STATUS, {
  update(cache, { data: { unitUpdateById } }) {
    setLoading(false)
    handleClose()
    const updatedUnit = { ...unitUpdateById }
    const updatedUnits = [...units]
    updatedUnits.find((unit) => unit._id === updatedUnit._id).status =
      updatedUnit.status
    setUnits(updatedUnits)
  }
})

错误被抛出为

caught (in promise) ApolloError: Cannot assign to read only property 'status' of object '#<Object>'
    at new ApolloError2 (index.ts:72:5)
    at Object.error (QueryManager.ts:327:32)
    at notifySubscription (module.js:137:18)
    at onNotify (module.js:176:3)
    at SubscriptionObserver2.error (module.js:229:5)
    at asyncMap.ts:44:28

现在,我知道错误是由于状态的不变性而引发的,但我不是已经在上面的代码中制作了所需的副本吗?

reactjs apollo immutability react-apollo
1个回答
0
投票

展开数组时,您正在创建一个新数组,其中包含与旧数组相同的对象(因此对象仍然是不可变的)。

你要找到要更新的item,展开并更新它,然后用更新的对象替换旧的对象到一个更新的数组中。

最后,用新的(更新的)数组调用更新函数:

const [releaseHold] = useMutation(UPDATE_UNIT_STATUS, {
  update(cache, { data: { unitUpdateById } }) {
    setLoading(false)
    handleClose()
    // find the item index
    const index = units.findIndex(({ _id }) => _id === unitUpdateById._id)
    // create updated item, from existing item + update
    const updatedUnit = { ...units[index], ...unitUpdateById }
    // copy the array
    const updatedUnits = [...units]
    // replace the old item with the updated one in the array copy
    updatedUnits.splice(index, 1, updatedUnit)
    // update the array
    setUnits(updatedUnits)
  }
})
© www.soinside.com 2019 - 2024. All rights reserved.