• 카테고리

    질문 & 답변
  • 세부 분야

    프론트엔드

  • 해결 여부

    해결됨

context 사용 시 에러가납니다.

20.04.09 14:29 작성 조회수 2.23k

0

강사님이 만드신 소스에서 그냥 간단하게 + - 되는 카운터 기능의 예제를 진행중입니다.

역시  hooks를 이용하려구 하구요.

// src/index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import StoreProvider from './Context';

ReactDOM.render(
  <StoreProvider>
    <App />,
  </StoreProvider>,
  document.getElementById('root'),
);

-------------------------------------------------------------------------

// src/Context.js

import React, { createContext } from 'react';
import { counterStore } from './store/counterStore';

export const storeContext = createContext({ counterStore });

export const StoreProvider = ({ children }) => {
  return <storeContext.Provider>{children}</storeContext.Provider>;
};

export default StoreProvider;

-------------------------------------------------------------------------

// src/App.js

import React from 'react';
import { useObserver } from 'mobx-react';
import useStore from './useStore';
// import { counterStore } from './store/counterStore';

function App() {
  const { counterStore } = useStore();

  return useObserver(() => (
    <div>
      <h1>{counterStore.number}</h1>
      <button onClick={counterStore.increase}>+1</button>
      <button onClick={counterStore.decrease}>-1</button>
    </div>
  ));
}

export default App;

-------------------------------------------------------------------------

// src/store/counterStore.js

import { observable } from 'mobx';

const counterStore = observable({
  number: 0,
  increase() {
    counterStore.number++;
  },
  decrease() {
    counterStore.number--;
  },
});

export { counterStore };

-------------------------------------------------------------------------

// src/useStore.js
import { useContext } from 'react';
import { storeContext } from './Context';

const useStore = () => {
  const { counterStore } = useContext(storeContext);

  return { counterStore };
};

export default useStore;

-------------------------------------------------------------------------

TypeError: Cannot destructure property 'counterStore' of 'Object(...)(...)' as it is undefined.

실행시 위와 같이 디스트럭처링을 할 수 없다고 나옵니다.

그래서 위의  src/useStore.js 부분에서 디스트럭처링 하지 않고 그냥 하게되면

// src/useStore.js
import { useContext } from 'react';
import { storeContext } from './Context';

const useStore = () => {
  const counterStore = useContext(storeContext);

  return { counterStore };
};

export default useStore;

TypeError: Cannot read property 'number' of undefined

Context API를 사용하지 않을 경우 스무스하게 잘 되는데 Context만 이용하려 하니 게속 에러가 발생합니다..

×

답변 4

·

답변을 작성해보세요.

1

import { useLocalStore } from 'mobx-react';
import React from 'react';
import counterStore from './counterStore';

export const storeContext = React.createContext(null);

export const StoreProvider = ({ children }) => {
  const store = useLocalStore(counterStore);

  return (
    <storeContext.Provider value={store}>
      {children}
    </storeContext.Provider>
  );
};

export default StoreProvider;​

Provider에 store을 안 넣으셨네요.

import * as React from 'react';
import { storeContext } from './Context';

function useStore() {
  const store = React.useContext(storeContext);
  if (!store) {
    // this is especially useful in TypeScript so you don't need to be checking for null all the time
    throw new Error('useStore must be used within a StoreProvider.');
  }
  return store;
}

export default useStore;

1

useStore에서 useContext쓰실 필요없이 그냥 import하셔서 return { counterStore }만 하셔도 됩니다.

https://github.com/ZeroCho/redux-vs-mobx/blob/master/8.mobx-react/useStore.js

0

혁999님의 프로필

혁999

질문자

2020.04.09

해결되었습니다. 감사합니다!

0

혁999님의 프로필

혁999

질문자

2020.04.09

말씀하신대로 하는 경우는 Context.js 도 필요없고 App.js에서 Provider가 전혀 안쓰이는것과 다름이 없는것 아닌가요? Context 자체를 안쓰고 커스텀훅만 사용할 경우 잘 되는 것 같습니다... 그런데 저는 Context를 한번 사용해보고 싶어서요.