reactjs - react app中的localForage:self未定义
问题描述
我正在尝试在 reactjs 应用程序中使用localForage。调用setItem
然后getItem
只工作一次。设置的值setItem
由 正确恢复getItem
。如果之后再次调用它们,TypeError
则抛出 a:
TypeError: self is undefined localforage.js:1012
可以使用最小的 reactjs 应用程序重现该错误,这里只是一个功能组件。
当组件被渲染时,它调用setItem
and 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;
推荐阅读
- android - 使用 zxing 生成热点或 wifi 二维码
- python - 如何从四个给定的选项中决定应该做出哪个决定?
- c - 如何将结构地址初始化为数组指针?
- sql-server - 当事件值为空时如何获取事件头值
- algorithm - 计算二叉树中的节点数 O(logn)^2
- python - 将 statsmodels 回归参数格式化为文本字符串以获得拟合方程
- python - 使用 SQLalchemy 在 Python 中 True 语句为 False ......为什么?
- flask - 如何从 Flask API 检测外部数据库更改
- asp.net - InvalidOperationException:未找到连接字符串“DefaultConnection”
- javascript - 如何使用 const 的值调用对象的元素?