Reducer

25 年 7 月 15 日 星期二
111 字
1 分钟

Reducer

https://zh-hans.react.dev/reference/react/useReducer#dispatch

useReducer

react
  const [{ cities, isLoading, currentCity }, dispatch] = useReducer(
    reducer,
    initialState
  );
react
const [state, dispatch] = useReducer(reducer, initialArg, init?)
react
function reducer(state, action) {
  switch (action.type) {
    case "loading":
      return {
        ...state,
        isLoading: true,
      };

    case "cities/loaded":
      return {
        ...state,
        isLoading: false,
        cities: action.payload,
      };

    case "city/loaded":
      return {
        ...state,
        isLoading: false,
        currentCity: action.payload,
      };

    case "city/created":
      return {
        ...state,
        isLoading: false,
        cities: [...state.cities, action.payload],
      };

    case "city/deleted":
      return {
        ...state,
        isLoading: false,
        cities: state.cities.filter((city) => city.id !== action.payload),
      };

    case "rejected":
      return {
        ...state,
        isLoading: false,
        error: action.payload,
      };

    default:
      throw new Error("Unknown action type");
  }
}
react
const initialState = {
  cities: [],
  isLoading: false,
  currentCity: {},
  error: "",
};
react
dispatch({ type: "loading" });

文章标题:Reducer

文章作者:Sirui Chen

文章链接:https://blog.siruichen.me/posts/reducer[复制]

最后修改时间:


商业转载请联系站长获得授权,非商业转载请注明本文出处及文章链接,您可以自由地在任何媒体以任何形式复制和分发作品,也可以修改和创作,但是分发衍生作品时必须采用相同的许可协议。
本文采用CC BY-NC-SA 4.0进行许可。