我正在制作一个配方盒项目,我有一个配方状态,其中包含一组配方对象。
我使用saveToLocal函数将当前状态保存到本地存储中,如下所示:
saveToLocal = () => {
const local = this.state.recipe;
localStorage.setItem("recipe", JSON.stringify(local));
}
然后将其传递回添加,编辑或删除新配方的函数
addNewRecipe = (newRecipe) => {
this.setState({
recipe: [...this.state.recipe,newRecipe]
}, this.saveToLocal);
}
editRecipe = (recipe) => {
let selectedRecipe =this.state.recipe.find(obj=>obj.count==recipe.count)
let editedRecipe = Object.assign(selectedRecipe,recipe);
this.setState(Object.assign(this.state.recipe,editedRecipe),this.saveToLocal)
}
deleteRecipe = (recipe) => {
let arr = this.state.recipe.filter(obj => obj.count !== recipe.count);
}
但是,这在我刷新应用程序时不起作用,但是当我在检查工具中检查本地存储时,该本地存储仍然具有配方数据。解决此问题的方法是什么?
谢谢
如果我理解正确,则希望在刷新时保存已保存的配方。您应该使用componentDidMount并从localStorage获取配方,然后根据此设置状态。
componentDidMount() {
const recipe = JSON.parse( localStorage.getItem( "recipe" ) );
this.setState( { recipe } );
}
您可以检查配方并有条件地渲染组件:
render() {
if( !this.state.recipe.length ) {
return <p>No recipe</p>;
// or you can use a spinner here
}
return { how you handle your recipe here, map it etc. }
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句