Fil*_*lth 7 javascript local-storage reactjs
在整个用户旅程中输入新数据时,如何更新本地存储项或对象的某些属性,并且不会丢失之前输入的内容或用户决定更新?
我的 5 个容器之旅包括要求用户输入以下内容:
在第一个视图中,我创建了本地存储对象/项目,用于在函数中设置名称handleSubmit。
处理提交(事件){ event.preventDefault();
//Profile object
let profile = { 'name': this.state.name, 'avatar': null, 'genres': '' };
// Put the object into storage
localStorage.setItem('profile', JSON.stringify(profile));
// Retrieve the object from storage
var retrievedObject = localStorage.getItem('profile');
//Log object
console.log('retrievedObject: ', JSON.parse(retrievedObject));
//On form submission update view
this.props.history.push('/profile/hello');
Run Code Online (Sandbox Code Playgroud)
}
在我的第二个视图中,我只想更新avatar属性并保留用户在前一个视图中输入的内容。
我在 handleSelect 函数中执行此操作,如下所示:
handleSelect(i) {
let selectedAvatarId;
let avatars = this.state.avatars;
avatars = avatars.map((val, index) => {
val.isActive = index === i ? true : false;
return val;
});
this.setState({
selectedAvatarId: selectedAvatarId
})
//Profile object
let profile = { 'avatar': i };
//Update local storage with selected avatar
localStorage.setItem('profile', JSON.stringify(profile));
}
Run Code Online (Sandbox Code Playgroud)
您需要从 localStorage 读取现有值,将其解析为 JSON,然后操作数据,然后将其写回。有许多库可以轻松使用 localStorage,但类似的东西应该作为通用函数工作:
function updateProfile = (updatedData) => {
const profile = JSON.parse(localStorage.getItem('profile'));
Object.keys(updatedData).forEach((key) => {
profile[key] = updatedData[key];
});
localStorage.setItem('profile', JSON.stringify(profile));
}
Run Code Online (Sandbox Code Playgroud)
如果你使用对象传播,它看起来也会干净得多:
function updateProfile = (updatedData) => {
const profile = {
...JSON.parse(localStorage.getItem('profile')),
...updatedData
};
localStorage.setItem('profile', JSON.stringify(profile));
}
Run Code Online (Sandbox Code Playgroud)
上面的代码中可能应该有一些安全检查,但希望能给您一个起点的想法。