【发布时间】:2018-11-15 01:19:31
【问题描述】:
如何在整个用户旅程中输入新数据时更新本地存储项目或对象的某些属性,而不丢失之前输入的内容或如果用户决定更新?
我的 5 个容器之旅,包括要求用户输入以下内容:
- 名称:字符串
- 头像:整数
- 最喜欢的流派:多个字符串
在第一个视图中,我创建了在 handleSubmit 函数中设置名称的本地存储对象/项目。
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');
}
在我的第二个视图中,我只想更新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));
}
【问题讨论】:
-
有点旁注,但你为什么要在整个过程中使用 localStorage?您拥有更快、更可靠的组件状态。只需将数据设置为包含组件的状态,并在完成后将其保存到 localStorage
-
很好的问题 - 不幸的是,我没有使用主父容器设置我的容器,因此它们都可以共享状态。另一种方法是建立一个商店,但这只是一个原型,现在设法让它工作。谢谢!
标签: javascript reactjs local-storage