【问题标题】:How to save a nested object in state in React?如何在 React 中保存嵌套对象的状态?
【发布时间】:2021-12-29 09:50:21
【问题描述】:

有没有一种简单的方法来保存/更新整个对象模型的状态?每次更新对象属性时,我都想保存此架构的快照。我已经有其他组件更新了架构属性(isComplete、progress),但我不知道如何将整个架构保存到状态,这样当我刷新时,所有进度仍然存在?

我想我需要一个带有 setSchema() 的 useEffect 钩子,也许还需要一个扩展运算符?我还没有数据库,所以我现在想将更新的架构存储在本地存储中。

   
   import course from "./data/index";

   const [schema, setschema] = useState(course);

   useEffect(()=>{
    setschema(???)
   })

const course = {
  courseName: "Course 1",
  courseModules: [
    {
      moduleName: "Module1",
      moduleLessons: [
        {
          lessonName: "Introduction",
          lessonData: Lesson1,
          isComplete: false,
          progress: 0,
        },
        {
          lessonName: "Overview",
          lessonData: Lesson2,
          isComplete: false,
          progress: 0,
        },
 
      ],
      isComplete: false,
      progress: 0,
    },
   
    {
      moduleName: "Module 2",
      moduleLessons: [
        {
          lessonName: "Lesson 1",
          lessonData: "hello There",
          isComplete: false,
          progress: 0,
        },
        {
          lessonName: "Lesson 2",
          lessonData: "hello There",
          isComplete: false,
          progress: 0,
        },
      ],
      isComplete: false,
      progress: 0,
    },
   
  ],
  isComplete: false,
  progress: 0,
};

【问题讨论】:

    标签: reactjs object local-storage state schema


    【解决方案1】:

    不确定我是否遵循,但如果我理解正确,您希望在每次更新时将 schema 保存到本地存储?

    可以这样做:

      useEffect(() => {
        localStorage.setItem("schema", JSON.stringify(schema));
      }, [schema]);
    

    【讨论】:

    • 是的,它是 get 和 set 我意识到这个问题很愚蠢。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-09
    • 2020-11-13
    • 2021-09-03
    • 1970-01-01
    • 2020-04-01
    • 2020-07-31
    相关资源
    最近更新 更多