如何在 React 中使用 useReducer 更新嵌套对象?

how to update nested object with useReducer in React?

如何使用这个 use reducer 更新 courseName? 错误:“无法在字符串“science”的 courseName 上创建 属性。 我假设我没有正确访问它?我一直在使用 useState 但我想学习 useReducer 来处理更复杂的对象。

import React, { useReducer } from "react";

function reducer(state, action) {
  switch (action.type) {
    case "update":
      return { object: (state.object.courseName = "Science") };

    default:
      return state;
  }
}

export default function TestPage() {
  const object = {
    courseName: "Mathematics",
    courseModules: [
      {
        moduleName: "module1",
        isComplete: false,
        lessons: [
          {
            lessonName: "Lesson1",
            isComplete: false,
            progress: 0,
          },
        ],
      },
    ],
  };

  const [state, dispatch] = useReducer(reducer, { object });

  function updateName() {
    dispatch({ type: "update" });
  }

  return (
    <div>
      <h1>{object.courseName}</h1>
      <button onClick={updateName}>submit</button>
    </div>
  );
}

您可以展开您的对象并只覆盖一个值。

  switch (action.type) {
    case "update":
      return { ...state, object: { ...state.object, courseName: "Science"}};
    default:
      return state;
  }