Ниже приведен мой пример кода при использовании контекста
Я создал класс с именем createDataContext
, который имеет следующий код
import React, { useReducer } from "react";
export default (reducer, actions, defaultValue) => {
const Context = React.createContext();
const Provider = ({ children }) => {
const [state, dispatch] = useReducer(reducer, defaultValue);
const boundActions = {};
for (let key in actions) {
boundActions[key] = actions[key](dispatch);
}
return (
<Context.Provider value={{ state, ...boundActions }}>
{children}
</Context.Provider>
);
};
return { Context: Context, Provider: Provider };
};
Ниже приведен код для моего AuthContext
файла
const authReducer = (state, action) => {
switch (action.type) {
case "error":
return {
...state,
...{ loading: false },
...{ errorMessage: action.payload }
};
case "customerMobileNumberLogIn":
return {
...state,
...{ data: action.payload },
...{ loading: false },
...{ errorMessage: "" }
};
case "inProgress":
return { ...state, ...{ loading: true }, ...{ errorMessage: "" } };
default:
return state;
}
};
const customerMobileNumberLogin = dispatch => {
..do api call with axios
}
export const { Provider, Context } = createDataContext(
authReducer,
{
customerMobileNumberLogin
},
[]
);
Я использую ReactRouter
import { Provider as AuthProvider } from "./context/AuthContext";
ReactDOM.render(
<AuthProvider>
<Router>
<RootWithAuth />
</Router>
</AuthProvider>,
document.getElementById("root")
);
Теперь предположим, что у меня много вызовов API, и я решил создать отдельный файл context
для каждого вызова API, не замедлится ли этот подход? мое приложение? context
API вызывает ту же проблему, что и redux
.