【发布时间】: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