我正在尝试在我的反例中使用context api
或useContext
。实际上我用0
initialize
我的值。点击按钮我想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/@seantheel/react-hooks-s-state management-secontext-useeeffect-sereducer-a75472a862fe但是下面的代码笔不起作用?
您与命名不一致:
const { loadingCount } = useLoadingState();
const { showLoading, hideLoading } = useLoadingActions();
https://codesandbox.io/s/inspiring-drake-18t12?file=/src/counter.js