如何使接收所有 3 个值的 useReducer 的文档示例正常工作?

How can I make the documentations example of useReducer which is receiving all 3 values work?

为了让它工作我尝试了很多方法,我只是不明白“init”是如何工作的,我怎样才能给它添加任何值以便应用程序可以运行?

这是我正在尝试做的一个例子:

import { useReducer } from "react";

function init(initialCount) {
  return { count: initialCount };
}

function reducer(state, action) {
  switch (action.type) {
    case "increment":
      return { count: state.count + 1 };
    case "decrement":
      return { count: state.count - 1 };
    case "reset":
      return init(action.payload);
    default:
      throw new Error();
  }
}

function CounterFunction({ initialCount }) {
  const [state, dispatch] = useReducer(reducer, initialCount, init);
  return (
    <>
      Count: {state.count}
      <button
        onClick={() => dispatch({ type: "reset", payload: initialCount })}
      >
        Reset
      </button>
      <button onClick={() => dispatch({ type: "decrement" })}>-</button>
      <button onClick={() => dispatch({ type: "increment" })}>+</button>
    </>
  );
}

export function Counter() {
  return (
    <>
      <CounterFunction />
    </>
  );
}

您目前正在做的是惰性初始化。它允许您在传递 useReducer 之前操纵它的初始值。如果你愿意,你可以跳过它,只写 reducer 的初始状态(可以是字符串、数字或对象之类的任何东西,毕竟它与 useState 非常相似,但能够通过传递更改类型轻松设置它(动作)).

示例:useReducer(dispatchHandler, {name: "hello"})

调用CounterFunction时代码缺少initialCount={0},所以完整的代码解决方案如下:

import { useReducer } from "react";

function init(initialCount) {
  return { count: initialCount };
}

function reducer(state, action) {
  switch (action.type) {
    case "increment":
      return { count: state.count + 1 };
    case "decrement":
      return { count: state.count - 1 };
    case "reset":
      return init(action.payload);
    default:
      throw new Error();
  }
}

function CounterFunction({ initialCount }) {
  const [state, dispatch] = useReducer(reducer, initialCount, init);
  return (
    <>
      Count: {state.count}
      <button
        onClick={() => dispatch({ type: "reset", payload: initialCount })}
      >
        Reset
      </button>
      <button onClick={() => dispatch({ type: "decrement" })}>-</button>
      <button onClick={() => dispatch({ type: "increment" })}>+</button>
    </>
  );
}

export function Counter() {
  return (
    <>
      <CounterFunction initialCount={0} />
    </>
  );
}