我正在尝试使用 localForage在reactjs应用程序中。调用 setItem
然后调用 getItem
只会执行一次。 getItem
可以正确恢复使用 setItem
设置的值。如果此后再次调用它们,则会抛出 TypeError
:
TypeError: self is undefined localforage.js:1012
可以使用最小的reactjs应用程序重现该错误,这里只是一个功能组件。
渲染组件时,它会调用 setItem
和 getItem
。
它会在单击按钮时重新呈现,并再次调用 setItem
和 getItem
。这会导致 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;
最佳答案
不知何故,单独导入方法时它会在内部丢失上下文,但在整体导入 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;
关于reactjs - react 应用程序中的localForage : self is undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61066019/