【问题标题】:issue where a constant value becomes a reference, or re-assigning a constant常量值成为引用或重新分配常量的问题
【发布时间】:2020-10-27 06:36:51
【问题描述】:

所以我不完全确定发生了什么或如何解释它,但是,

TL;DR 版本,基本上是这样的

const {a} = {a: 'd'}

a = "12"
console.log(a)
// returns "12"

我正在尝试将publicItemList 的状态更新为用户输入。 同时useQuery()每500ms重新获取一次数据并更新data的值。

我期望发生的是当我更改publicItemList 并且查询挂钩再次运行时,publicItemList 状态应该更新为data 的新值。 因此,如果我在publicItemList 上设置了一个勾选框,当useQuery() 再次运行时,它应该再次取消勾选,因为勾选从未保存到数据库中。

实际发生的情况是,当我用勾号更改 publicItemList 时,它会在查询钩子运行时取消勾号,而最奇怪的是......

如果我退出dataconsole.log(data[where ever that tick is].isTicked),它将返回我在publicItemList 中所做的更改,这怎么可能?

  const [publicItemList, setPublicItemList] = useState<ItemProps[]>([])

  const { loading: tripLoading, error: tripError, data, refetch } = useQuery(getTrip, {
    variables: { id: tripId },
    pollInterval: 500,
    notifyOnNetworkStatusChange: true,
    onCompleted: data => {
      const { trip } = data
      const publicList = trip.packingLists.find((x) => x.isPublicList)
      setPublicItemList(publicList.items)
    },
    onError: error => console.log(error),
  })

  const insertPublicItemListSingle = (inputItem: ItemProps, removing?: boolean) => {
    const newItemList: ItemProps[] = publicItemList.slice()
    const foundIndex = newItemList.findIndex(item => item.id === inputItem.id)

    if (foundIndex.toString()) {
      // Update
      newItemList[foundIndex] = inputItem

    setPublicItemList(newItemList)
  }

  const checkItem = (item: ItemProps) => { // <=== this is a user action
    const { packed } = item
    item.packed = !packed
    packed
      ? item.packedBy = ""
      : item.packedBy = userData.name
    insertPublicItemListSingle(item)
  }

附加信息, 在 iOS 模拟器上使用 Apollo 客户端进行 react-native

【问题讨论】:

    标签: javascript reactjs react-native apollo-client


    【解决方案1】:

    在我的电脑里:

    const {a} = {a: 'd'}
    
    a = "12"
    

    未捕获的类型错误:赋值给常量变量。

    这不是你的问题。 publicItemList是一个数组,不能赋值,但是可以改变里面的内容

    const a = [1, 2, 4];
    a = [2, 4, 6]; // error
    a[0] = 2;
    a[1]= 4;
    a[2] = 6;
    cosole.log(a); // [2, 4, 6]
    

    在我看来,setPublicItemList 不要重新分配你的publicItemList,它会改变内容。

    (IDKreact-native)

    【讨论】:

    • 但我使用的是setPublicItemList 而不是重新分配publicItemList
    • 是的,我的意思是setPublicItemList 分配publicItemList 的内容(如publicItemList[0] = newArrray[0])
    【解决方案2】:

    我发现了问题,其中有一个突变

      const checkItem = (item: ItemProps) => {
        const { packed } = item
        item.packed = !packed
        packed
          ? item.packedBy = ""
          : item.packedBy = userData.name
        insertPublicItemListSingle(item)
      }
    

    突变总是让你咬牙切齿

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-08
      • 1970-01-01
      • 2014-03-03
      • 2013-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-20
      相关资源
      最近更新 更多