작성
·
722
답변 1
1
Context
와 dispatch
에 타입을 잘 넣어주시면 됩니다 :)
찾으신것처럼 Context
에 타입을 null
로 주셔서 아무것도 없는데 dispatch
를 꺼내쓰려고 해서 생긴 오류입니다.
참고할만한 예제 코드를 드리겠습니다. 연습해보시고 적용하시면 좋을듯 해요. 화이팅입니다!
import { Dispatch, createContext, useContext, useReducer } from 'react';
type Action = { type: 'increment' } | { type: 'decrement' };
function counterReducer(state: number, action: Action): number {
switch (action.type) {
case 'increment':
return state + 1;
case 'decrement':
return state - 1;
default:
throw new Error('Unhandled action type');
}
}
const initialState = 0;
type CounterContextType = {
state: number;
dispatch: Dispatch<Action>;
};
const CounterContext = createContext<CounterContextType>({
state: initialState,
dispatch: () => {},
});
function CounterProvider(props: { children }) {
const [state, dispatch] = useReducer(counterReducer, initialState);
const value = { state, dispatch };
return <CounterContext.Provider value={value} {...props} />;
}
function useCounterContext(){
const context = useContext(CounterContext);
return context
}
function Counter() {
const {state, dispatch} = useCounterContext();
const handleIncrement = () => dispatch({ type: 'increment' });
const handleDecrement = () => dispatch({ type: 'decrement' });
return (
<>
<h1>{state}</h1>
<button onClick={handleIncrement}>+</button>
<button onClick={handleDecrement}>-</button>
</>
);
}
function App() {
return (
<CounterProvider>
<Counter />
</CounterProvider>
);
}
export default App;