我正在学习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");
}
};
1条答案
按热度按时间xlpyo6sf1#
check
似乎不是json。请在分配给状态之前检查它是否为json