【问题标题】:Can't convert null or undefined with React Hooks无法使用 React Hooks 转换 null 或 undefined
【发布时间】:2021-09-25 06:46:44
【问题描述】:

我有一个状态,我用 Hooks 在 react 中设置,像这样:

useEffect(() => {
        if (uid !== null) {
            axios.get(`${process.env.REACT_APP_API_URL}api/balance/${uid}`)
                .then((res) => {
                     setUserWalletIncomes(res.data[0].incomes)
                })
        }
    }, [uid])

这个状态,要清楚,给我这个:

一切正常,我可以删除我的收入等。

问题是,当我删除最后一个收入(这使状态为空)时,我有这个错误并且页面空白:

TypeError: Cannot convert undefined or null to object

这是我的删除请求:

const handleDeleteIncome = (key) => {
        let data = { [key]: "" }
        axios({
            method: "delete",
            url: `${process.env.REACT_APP_API_URL}api/balanceOneIncome/${uid}`,
            data: data
        }).then((res) => {
            if {(userWalletIncomes === null) setUserWalletIncomes({})}
            setUserWalletIncomes(res.data[0].incomes)
            setformIncomes(false)
        })
    }

我尝试添加条件:if {(userWalletIncomes === null) setUserWalletIncomes({})},但我仍然遇到同样的问题。

有人可以帮我解决这个问题吗?

[编辑]

我的状态是这样初始化的:

const [userWalletIncomes, setUserWalletIncomes] = useState({})

PS:如果我重新加载页面,一切都很好。

【问题讨论】:

  • 如何迭代渲染中的值?
  • 我认为您的应用程序中可能还有其他可以改进的地方,但是对于低分辨率的快速“修复”,您可以扩展您的条件以包括 null undefined: if (userWalletIncomes === null || userWalletIncomes === undefined) setUserWalletIncomes({}),或者只是if (!userWalletIncomes) setUserWalletIncomes({})。您还应该在该语句之外 return 然后避免继续执行导致错误的原因。此外,您的 {} 大括号在这个 if 语句周围很奇怪,我希望这是一个错字。
  • 能否请您在 res.log 上做一个 console.log。数据?。也许您需要在获取第一个元素之前添加 Array.isArray(res. data) ?
  • @AlexanderStaroselsky 是的,Object.entries
  • 这是问题所在,而不是问题所在。要么始终设置为至少为空的对象,要么进行条件渲染以仅在对象条目至少为真时才使用它。

标签: reactjs axios react-hooks state


【解决方案1】:

这是问题吗? (我假设您并没有像您的帖子中那样使用奇怪的 {} 大括号定位?)

你有这个:

if (userWalletIncomes === null) { setUserWalletIncomes({}) }
setUserWalletIncomes(res.data[0].incomes)

但是在您调用setUserWalletIncomes({}) 之后,您会失败并立即再次调用它,并在下一行使用空值。也许您只需要在将其设置为空对象后显式返回?或者,为了简化,您可以删除该条件并改为这样做:

setUserWalletIncomes(res.data[0].incomes || {})

【讨论】:

  • 我找到了解决方案,离您的建议不远。非常感谢:)
【解决方案2】:

回答,如果它对某人有帮助,是这样的:

const handleDeleteIncome = (key) => {
        let data = { [key]: "" }
        axios({
            method: "delete",
            url: `${process.env.REACT_APP_API_URL}api/balanceOneIncome/${uid}`,
            data: data
        }).then((res) => {
            if (res.data[0].incomes) {
                setUserWalletIncomes(res.data[0].incomes)
            } else {
                setUserWalletIncomes({})
            }
        })
    }

只是一个判断响应是否为空的条件,然后将状态设置为空对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-02
    • 2019-10-25
    • 2020-05-03
    • 1970-01-01
    • 2021-07-29
    • 2020-07-19
    • 2020-12-06
    • 1970-01-01
    相关资源
    最近更新 更多