#reactjs #redux #react-router #react-hooks #use-context
#reactjs #сокращение #react-маршрутизатор #реагирующие хуки #использовать-context
Вопрос:
Я пытаюсь использовать context api
или use of useContext
в моем примере счетчика.На самом деле я initialize
использую значение с 0
.При нажатии кнопки я хочу increase
значение счетчика?Но я не могу этого сделать.
вот мой код 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 не работает?
Комментарии:
1. Ваш код codesandbox не завершен, пожалуйста, исправьте это
2. codesandbox.io/s/happy-spence-qbmps?file=/src/context.js
3. извините. пожалуйста, проверьте сейчас
Ответ №1:
Вы не согласны с наименованием:
const { loadingCount } = useLoadingState();
const { showLoading, hideLoading } = useLoadingActions();
https://codesandbox.io/s/inspiring-drake-18t12?file=/src/counter.js