【问题标题】:how to use context api in react in counter example?如何在反例中使用上下文 API 做出反应?
【发布时间】:2020-12-24 09:25:13
【问题描述】:

我想在我的反例中使用context apiuseContext。实际上我initialize 我的值是0。点击按钮时我想increase 计数器值?但我是做不到。

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

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

但我做错了

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

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不起作用?

【问题讨论】:

标签: reactjs redux react-router react-hooks use-context


【解决方案1】:

你与命名不一致:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-26
    • 2021-10-30
    • 1970-01-01
    • 2021-02-18
    • 1970-01-01
    • 1970-01-01
    • 2017-07-28
    • 1970-01-01
    相关资源
    最近更新 更多