【问题标题】:React, why is setting the state as an array of undefined values?React,为什么将状态设置为未定义值的数组?
【发布时间】:2020-07-19 00:04:53
【问题描述】:

我的应用程序从数据库中获取已完成的任务,并将它们存储在本地存储中,每次有人执行另一个任务时,我都会更新已完成任务的状态,以及本地存储,但是在某个时刻里面的值数组变得未定义,这是更新状态和本地存储的函数

  const completeTask = useCallback(
    (data) => {
      data["event"] = eventID
      data["attendee"] = user._id

      const actionType = data.eventActivity
        ? data.eventActivity
        : data.exhibitor
        
      const taskData = tasks.filter((task) => task.key === data.name)[0]

      if (
        !completedTasks.includes(data.name + actionType) &&
        !completedTasks.includes(data.name) &&
        tasks && taskData
      ) {
        data["action"] = taskData.id
        data["points"] = taskData.points

        api.post("/api/gamification-log", { data: data }).then((response) => {
          
          localStorage.setItem(
            "Gamification:pontuation",
            JSON.stringify({
              logs: [...completedTasks, data.name + actionType],
              pontuation: prevPontuation + data.points,
            })
          )
          setUserPontuation((prevState) => prevState + data.points)
          
          setCompletedTasks((oldTasks) => [...oldTasks, data.name + actionType])
        })
      }
    },
    [eventID, user, completedTasks, tasks]
  )

它开始以正确的方式运行,completedTasks 数组看起来像这样

["visit_stand5eda6582e7c2deeb3cd09cf3","visit_stand5ebad3182e98903e662497ba"]

但是在调用这个函数几次之后,完成的任务数组变成了这个

["undefinedundefined", "undefinedundefined"]


**Update**

In the useEffect I was setting the state the wrong way, the problem is solved now

【问题讨论】:

  • 能否只包含与问题相关的代码?
  • 对不起,这是我第一次使用堆栈溢出,但我相信所有功能对于理解行为都很重要
  • @ViniciusBass 您的代码中的其他任何内容(此处未包含)是否调用 setCompletedTasks(例如当道具更改时)?
  • @DougNeiner 除了这个函数,只有 useEffect 调用 setCompletedTasks

标签: javascript reactjs local-storage state setstate


【解决方案1】:

我会说您没有传递有效的数据变量或无效的对象。

例如:如果data.eventActivity 未设置且data.exhibitor 未设置,则actionType 将为undefined

检查您传递给completeTask 函数的数据。

【讨论】:

  • 说的有道理,但是为什么它把数组的所有值都设置为undefinedundefined,甚至那些本来就正确的呢?
猜你喜欢
  • 2017-07-29
  • 2017-08-17
  • 1970-01-01
  • 2020-10-01
  • 1970-01-01
  • 2019-11-12
  • 1970-01-01
  • 2022-11-30
  • 2017-04-07
相关资源
最近更新 更多