강의

멘토링

로드맵

Cộng đồng Hỏi & Đáp của Inflearn

Hình ảnh hồ sơ của znrzl11157
znrzl11157

câu hỏi đã được viết

Các cậu cứ thoải mái làm backend nếu muốn, tớ không sao đâu vì tớ đã có Firebase rồi.

context로 관리 thông tin người dùng

useAuthContext 에서 dispatch 를 사용할 때 에러가 나요.

Viết

·

823

0

 

 

  const { dispatch } = useAuthContext();

 

위와 같이 사용했을 때 dispatch 아래에 밑줄이 생기는데

 

'null' 형식에 'dispatch' 속성이 없습니다.ts(2339)

const dispatch: any

 

와 같은 에러가 생깁니다.

(alias) const AuthContext: Context<null>
import AuthContext

 

이렇기 때문인 것 같은데 어떻게 수정해야할까요..

타입스크립트를 사용하고 있습니다.

reactfirebase

Câu trả lời 1

1


Contextdispatch에 타입을 잘 넣어주시면 됩니다 :)
찾으신것처럼 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;
Hình ảnh hồ sơ của znrzl11157
znrzl11157

câu hỏi đã được viết

Đặt câu hỏi