0

我正在尝试在我的计数器示例中使用context api或使用。实际上, 我使用.On 按钮单击我的值我想要计数器值?但我无法做到这一点。useContextinitialize0increase

这是我的代码 https://codesandbox.io/s/happy-spence-qbmps?file=/src/context.js

我举了一个例子,user增加计数器以显示类似于增加和减少计数器的加载器。

但我做错了什么

你能告诉我如何在context不使用的情况下使用 api增加和减少计数器值吗redux

import React, { useReducer, useContext, createContext } from "react";

const LoadingStateContext = createContext();
const LoadingDispatchContext = createContext();
const initialState = {
  loadingCount: 0
};

function reducer(state, action) {
  switch (action.type) {
    case "SHOW_LOADER":
      return { ...state, loadingCount: state.loadingCount + 1 };
    case "HIDE_LOADER":
      return { ...state, loadingCount: state.loadingCount - 1 };
    default:
      return state;
  }
}

function LoadingProvider({ children }) {
  const [state, dispatch] = useReducer(reducer, initialState);

  const showLoading = () => dispatch({ type: "SHOW_LOADER" });
  const hideLoading = () => dispatch({ type: "HIDE_LOADER" });

  const actions = { showLoading, hideLoading };

  return (
    <LoadingStateContext.Provider value={state}>
      <LoadingDispatchContext.Provider value={actions}>
        {children}
      </LoadingDispatchContext.Provider>
    </LoadingStateContext.Provider>
  );
}

function useLoadingState() {
  const context = useContext(LoadingStateContext);
  if (context === undefined)
    throw Error('"useErrorState" should be used under "ErrorProvider"!');

  return context;
}

function useLoadingActions() {
  const context = useContext(LoadingDispatchContext);
  if (context === undefined)
    throw Error(
      '"useErrorActions" should be used under "ErrorDispatchContext"!'
    );

  return context;
}

export { LoadingProvider, useLoadingState, useLoadingActions };

我也看过这个教程

https://medium.com/@seantheurgel/react-hooks-as-state-management-usecontext-useeffect-usereducer-a75472a862fe 但下面的codepen不起作用?

4

1 回答 1

0

您与命名不一致:

const { loadingCount } = useLoadingState();
const { showLoading, hideLoading } = useLoadingActions();

https://codesandbox.io/s/inspiring-drake-18t12?file=/src/counter.js

于 2020-09-05T09:43:00.360 回答