【问题标题】:Using local storage in ReactJS在 ReactJS 中使用本地存储
【发布时间】:2023-03-10 15:40:01
【问题描述】:

我正在制作一个食谱盒项目,我有一个包含食谱对象数组的食谱状态。

我使用 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);
}

但是,当我刷新应用程序时,这不起作用,但是当我检查检查工具内的本地存储时,本地存储仍然有配方数据。有什么办法解决这个问题?

谢谢

【问题讨论】:

  • 您从哪里再次从 localStorage 获取项目?当您刷新应用时,您将失去您的状态。
  • 你想要发生什么?
  • 我想在刷新时保存食谱
  • 刷新时保存?从哪里保存到哪里?

标签: javascript reactjs local-storage


【解决方案1】:

保存到本地存储和从本地存储获取是两种不同的方法。

localStorage.setItem(‘recipe’, JSON.stringify(this.state.recipe)

const recipe = localStorage.getItem(‘recipe’)

this.setState({...recipe})

你不需要创建 saveToLocal 方法

【讨论】:

    【解决方案2】:

    如果我理解正确,您希望在刷新时保存食谱。您应该使用 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. }
    }
    

    【讨论】:

    • 既然 OP 使用的是 setState,这不应该在 componentDidUpdate 里面吗? (不是没有安装)。此外,他们已经在设置 ​​localStorage 之前更新了状态,因此无需在此处再次设置状态 - 这会不必要地导致组件重新渲染两次。
    • @TPHughes,我理解并假设 OP 想要在刷新应用程序后填充状态。刷新后,localStorage 上没有状态但有持久信息。因此,一旦应用程序启动或刷新,就可以在 componenetDidMount 中填充状态。 componentDidMount 在组件第一次挂载后运行,而不是每次状态更改时运行。应用启动后,这是获取远程数据的好地方。
    • 啊,是的,你完全正确。我自己误读了它 - 问题是他只想在刷新时检索它。这是很好的信息,我很抱歉。
    • 不用道歉:)
    【解决方案3】:

    然后您可以使用localStorage.getItem("recipe") 来检索它。在你的渲染函数中做一个控制台日志,并检查你浏览器的 JS 控制台。

    render() {
       console.log('recipe is', localStorage.getItem("recipe"))
    }
    

    您的 localStorage 将保留在磁盘上,直到您清除缓存。

    【讨论】:

    • 是的,它仍然会从 localStorage 中注销数据,但我不知道如何使用它们在应用中显示
    • 只需将localStorage.getItem("recipe") 分配给一个变量。您已经在发送到 localStorage 之前设置了状态,因此您可以使用this.state.recipe 检索它,但否则在render() 方法中的任何位置调用let foo = JSON.parse(localStorage.getItem("recipe")) 将允许您将配方对象用作fooJSON.parse() 将简单地获取 JSON 字符串并将其转换为您的对象。
    猜你喜欢
    • 1970-01-01
    • 2021-10-08
    • 2020-11-04
    • 2020-08-20
    • 2018-02-12
    • 1970-01-01
    • 2021-10-11
    • 2018-11-12
    • 1970-01-01
    相关资源
    最近更新 更多