我的authProvider如下所示:
import { AUTH_LOGIN, AUTH_LOGOUT, AUTH_GET_PERMISSIONS, AUTH_CHECK } from 'react-admin';
import { stringify } from 'query-string';
export default (type, params) => {
if (type === AUTH_LOGIN) {
const { username, password } = params;
const myBody = {
username: username,
password: password,
};
const request = new Request('http://myApi.loginUrl', {
method: 'POST',
body: JSON.stringify(myBody),
headers: new Headers({ 'Content-Type': 'application/json',
'Accept': 'application/json'}),
})
return fetch(request)
.then(response => {
if (response.status < 200 || response.status >= 300) {
throw new Error(response.statusText);
}
return response.json();
})
.then(json => { localStorage.setItem('userdata', JSON.stringify(json)); console.log(JSON.stringify(json)); return json; })
.then(({ token }) => {
localStorage.setItem('token', token);
});
}
if (type === AUTH_GET_PERMISSIONS) {
let newrole = localStorage.getItem('userdata');
newrole = JSON.parse(newrole);
if ( parseInt(newrole.is_admin) === 1 ) {
localStorage.setItem('role', 'admin');
} else {
localStorage.setItem('role', 'user');
}
const role = localStorage.getItem('role');
return Promise.resolve(role);
}
if (type === AUTH_CHECK) {
return localStorage.getItem('token')
? Promise.resolve()
: Promise.reject();
}
if (type === AUTH_LOGOUT) {
localStorage.removeItem('token');
localStorage.removeItem('role');
localStorage.removeItem('userdata');
return Promise.resolve();
}
return Promise.resolve();
}
我想在authProvider中的任何地方都将localStorage更改为sessionStorage,但是当我想重用它时,我会得到null。
我在多个地方(例如在仪表板上)使用“ userdata”条目,如下所示:
let userData = localStorage.getItem('userdata');
userData = JSON.parse(userData);
class Dashboard extends Component {
state = {
username: userData.name,
fullname: userData.fullname,
当我想像这样从会话中检索项目时,我得到的“名称”为空错误:
let userData = sessionStorage.getItem('userdata');
userData = JSON.parse(userData);
class Dashboard extends Component {
state = {
username: userData.name,
fullname: userData.fullname,
我做错了什么?
我还读到了某个位置,即在安装组件后,sessionStorage将起作用,这是定义sessionStorage的时刻。
这是否意味着我不能在authProvider中使用sessionStorage?