无法从 reducer 功能控制台记录状态?

can't console log state from reducer function?

我不明白为什么在 React 中设置这个 reducer 函数时状态没有改变。我只想通过控制台记录 reducer 函数的新状态?

const [lessonState, dispatchLesson] = useReducer(lessonReducer, {
    lesson: 0,
    isComplete: false,
  });

const lessonReducer = (state, action) => {
  if (action.type === "UPDATE") {
    return { lesson: action.lesson, isComplete: true };
  }
};

const initializeLesson = () => {
    dispatchLesson({ type: "UPDATE", lesson: 2 });
    console.log(lessonState);<------
};


//other stuff//
export default function Dashboard() {

  useEffect(() => {
    context.initializeCourse();
  }, []);

  return (
    <Fragment>
      <div className="dashboard">
        <h1>Hello</h1>
      </div>
    </Fragment>
  );
}

您无法在立即调度后获得更新的 reducer 状态。要获取更新状态数据,您可以执行以下操作:

  useEffect(() => {
    console.log("lessonState", lessonState);
  }, [lessonState]);

所以当状态更新时,这个useEffect会被触发,你会得到更新后的状态。