
import localForage from 'localforage';
import React from 'react';
import globalHook, { Store } from 'use-global-hook';
interface State {
isLoading: boolean;
isAuthenticated: boolean;
}
type Action = {
setIsLoading: (isLoading: boolean) => void;
setIsAuthenticated: (isAuthenticated: boolean) => void;
};
const authenticate = localForage
.getItem('token')
.then((value) => {
return value ? true : false;
})
.catch(function (err) {});
const initialState: State = {
isLoading: false,
isAuthenticated: false,
};
const actions = {
setIsLoading: (store: Store<State, Action>, isLoading: boolean) => {
store.setState({ ...store.state, isLoading });
},
setIsAuthenticated: (
store: Store<State, Action>,
isAuthenticated: boolean
) => {
store.setState({ ...store.state, isAuthenticated });
},
};
const useGlobal = globalHook<State, Action>(React, initialState, actions);
export default useGlobal;嗨,我正在用reactjs实现一个登录功能,并使用localforage来存储令牌。我在全局状态中有一个isAuthenticated状态。现在,我希望根据localForage是否具有令牌,将isAuthenticated initialValue值更改为true或false。因此,无论localForage是否有值,我都想返回一个布尔值。但现在它返回的是promise,而不是localForage的布尔值。提前感谢您的帮助
发布于 2020-12-10 20:16:41
我觉得你的身份验证函数有点问题。我要做的是,对一个函数进行身份验证,然后该函数调用localForage来获取令牌,然后返回令牌。
我做了一个使用localForage的快速示例。我首先在呈现组件时设置令牌,然后从localForage获取它。然后,它会正确地呈现该值,并且不需要执行任何其他操作。请以此为例。您也可以在here中找到它
import React, { useState, useEffect } from "react";
import localForage from "localforage";
export default function App() {
const [token, setToken] = useState("");
const [error, setError] = useState(null);
const authenticate = () => {
return localForage
.getItem("token")
.then((value) => setToken(value))
.catch((err) => setError(err));
};
useEffect(() => {
localForage.setItem("token", "token123");
authenticate();
}, []);
return (
<div className="App">
{error ? <p>Error {error}</p> : <p>Token: {token}</p>}
</div>
);
}https://stackoverflow.com/questions/65228691
复制相似问题