【发布时间】:2020-12-24 09:25:13
【问题描述】:
我想在我的反例中使用context api 或useContext。实际上我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