我使用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);
});
}
从你的try/catch
删除saveState()
。如果要在子组件树中的任何位置捕获JavaScript错误。并尝试在state
的saveState()
中进行控制。