React解析本地存储问题(未捕获(在承诺中)语法错误:意外标记“u”、“函数st ...”不是有效的JSON)

kgsdhlau  于 2022-11-19  发布在  React
关注(0)|答案(1)|浏览(299)

我正在学习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");
    }
  };
xlpyo6sf

xlpyo6sf1#

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));

相关问题