我正在學習 React 技巧,并嘗試讓我的應用程式在發出獲取請求之前檢查本地存盤。很確定我的代碼是可靠的,但我一直在 console.log 中收到此錯誤
VM79:1 Uncaught (in promise) SyntaxError: Unexpected token 'u', "function st"... is not valid JSON
at JSON.parse (<anonymous>)
at getPopular (Popular.jsx:19:1)
at Popular.jsx:13:1
我認為這與我的 if/else 有關。在實作它之前一切都很好,但是有了它(從我的本地主機查看)它不會從我正在使用的 api 獲取和顯示影像。誰能幫忙?
Popular.jsx
const Popular = () => {
const [popular, setPopular] = useState([]);
useEffect(() => {
getPopular();
}, []);
const getPopular = async () => {
const check = localStorage.getItem("popular");
if (check) {
setPopular(JSON.parse(check));
} else {
const url = "https://api.spoonacular.com/recipes/random";
const apiKey = process.env.REACT_APP_API_KEY;
const res = await fetch(`${url}?apiKey=${apiKey}&number=9`);
const data = await res.json();
localStorage.setItem("popular", JSON.stringify(data.recipes));
setPopular(data.recipes);
console.log("Restore popular");
}
};
uj5u.com熱心網友回復:
好像check不是 json。在分配給狀態之前檢查它是否是一個json
const isJson = (str) => {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
const getPopular = async () => {
const check = localStorage.getItem("popular");
if (check && isJson(check)) {
setPopular(JSON.parse(check));
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/534007.html
