首页 > 解决方案 > react app中的localForage:self未定义

问题描述

我正在尝试在 reactjs 应用程序中使用localForage。调用setItem然后getItem只工作一次。设置的值setItem由 正确恢复getItem。如果之后再次调用它们,TypeError则抛出 a:

TypeError: self is undefined localforage.js:1012

可以使用最小的 reactjs 应用程序重现该错误,这里只是一个功能组件。
当组件被渲染时,它调用setItemand getItem。它会在单击按钮setItemgetItem再次调用时重新呈现。这导致TypeError.

import React, { useState } from "react";
import { getItem, setItem } from "localforage";

function App() {
  const [state, setState] = useState(0);
  setItem("test", state).then(() => {
    console.log("used localForage");
  });

  getItem("test").then((val) => {
    console.log("got: ", val);
  });
  return (
    <button
      onClick={() => {
        setState(Math.floor(Math.random() * 10));
      }}
    >
      {state}
    </button>
  );
}

export default App;

这是代码沙盒上的在线版本

标签: reactjslocalforage

解决方案


当单独导入方法时,它以某种方式在内部丢失了上下文,在整体导入 localforage 时工作正常

import React, { useState } from "react";
import localforage from "localforage";

function App() {
  const [state, setState] = useState(0);
  localforage.setItem("test", state).then(() => {
    console.log("used localForage");
  });

  localforage.getItem("test").then(val => {
    console.log("got: ", val);
  });
  return (
    <button
      onClick={() => {
        setState(Math.floor(Math.random() * 10));
      }}
    >
      {state}
    </button>
  );
}

export default App;

推荐阅读