未处理的拒绝(类型错误):无法读取 null 的属性(读取"详细信息")



useEffect(()=>{document.title=View Orders | Bothub

fetch(`${backendAppUrl}/orders/all`, {
...getRequestParams("POST", {
uid: localStorage.uid,
idToken: localStorage.idToken,
user: 0,
pagination: 1,
}),
})
.then((res) => res.json())
.then(
(res) => {
console.log(res);
if (res.detail === "db-error" || res.detail === "forbidden") {
setError(true);
setLoading(false);
} else {
const val = res.data;
setOrders(val);
setLoading(false);
}
},
(err) => {
console.log(err);
setError(true);
setLoading(false);
}
);
// eslint-disable-next-line

},[]);

为什么它显示为这样并抛出错误?未处理的拒绝(TypeError):无法读取null的属性(读取"detail")

如果这在控制台中显示null

console.log(res);

然后JSON响应是空的(尽管我想在某种程度上仍然有效),并且没有可使用的对象。因此,代码需要能够处理res中的null值。例如:

if (res?.detail === "db-error" || res?.detail === "forbidden") {
setError(true);
setLoading(false);
} else {
const val = res?.data;
setOrders(val);
setLoading(false);
}

这使用了nullish-safe可选链接来检查res的属性,或者只返回null。因此,当resnull时,则if条件将是false,并且执行else块。

或者,如果您希望系统以不同的方式处理null,您可以在逻辑中执行该检查。例如:

if (!res) {
// respond to null in some way here
} else if (res.detail === "db-error" || res.detail === "forbidden") {
setError(true);
setLoading(false);
} else {
const val = res.data;
setOrders(val);
setLoading(false);
}

无论以何种方式构建它,关键是resnull,而您的代码假设它不是,这就产生了错误。

相关内容

最新更新