我正在使用localstorage.setItem()存储状态,该状态将在页面刷新时起作用,但在我的情况下localstorage无法正常工作。页面刷新时我的状态不是持久的。
我需要全局保存用户ID,这也需要在整个项目的页面刷新中保留。请帮助我解决此问题。
任何帮助,将不胜感激。
function setUserId(user_id = '', action) {
switch (action.type) {
case 'ADD_ID':
return user_id = action.id;
default:
return user_id = action.id;
}
}
const loadState = () => {
try {
const serializedState = localStorage.getItem("state");
if (serializedState === null) {
return undefined;
}
return JSON.parse(serializedState);
} catch (err) {
return undefined;
}
};
const store = createStore(setUserId,loadState());
function saveState(state) {
try {
let serializedState = JSON.stringify(state);
localStorage.setItem("state",serializedState);
}
catch (err) {
}
}
handleClick(event) {
let that = this;
axios.post(apiBaseUrl, payload)
.then(function (response) {
console.log(response);
if(response.status == 200){
console.log("Login successfull");
store.dispatch({
type: 'ADD_ID',
id: response.data.id
})
store.subscribe(() => {
//this is just a function that saves state to localStorage
saveState(store.getState());
});
that.setState({
isLoggedIn: true,
access_token: response.data.access_token,
user_id: response.data.id
})
}
else if(response.status == 204){
console.log("Username password do not match");
alert("username password do not match")
}
else{
console.log("Username does not exists");
alert("Username does not exist");
}
})
.catch(function (error) {
console.log(error);
});
}
答案 0 :(得分:0)
从您的try/catch
中删除saveState()
。如果要在子组件树的任何位置捕获JavaScript错误。并尝试在state
的{{1}}中进行控制台。