IT이야기

반응 후크(useState) 및 Mobx [mobx-react-lite 없음]

cyworld 2022. 3. 16. 22:04
반응형

반응 후크(useState) 및 Mobx [mobx-react-lite 없음]

내 리액션 애플리케이션(유형 설명 포함)에서 리액션 후크(특히 상태 사용)를 사용하여 폼 상태를 관리하고 한편 Mobx 스토어의 관찰 가능한 구성 요소로 사용하고 싶지만 오류가 발생함

후크는 기능 구성요소의 본체 안에서만 호출할 수 있다.

예를 들어 다음 구성 요소에서

import * as React from "react";
import { inject, observer } from "mobx-react";
import { MyStore } from "./MyStore";

interface IProps {
  myStore?: MyStore;
  id: string;
}

const MyComponent: React.FC<IProps> = props => {
  const [state, setState] = React.useState("");
  return (
    <div>
      <h1>{props.id}</h1>
    </div>
  );
};
export default inject("myStore")(observer(MyComponent));

나는 해결책을 보았지만 그것은 사용이었다.React.createContext저장소 클래스를 내보내는 경우Mobx와 Hooks에 대한 오래된 접근방식이 어디 있지 않은가?

여기 예를 위한 sanbox가 있다.

Mobx 버전을 언급하는 @Tholle 덕분에, Mobx 6가 출시되었으니 이 문제는 해결되었다.

mobx-react후크를 지원하지 않으며 mobx와 함께 후크를 사용하려면 github 문서에도 이러한 후크를 사용해야 한다.

그렇게 하기 위해 당신은 이용할 수 있다.React.createContext제공자 대신useContext대신에inject

인덱스.tsx

import * as React from "react";
import { render } from "react-dom";
import MyComponent, { Store } from "./MyComponent";

import "./styles.css";
import MyStore from "./MyStore";

function App() {
  const [state, setState] = React.useState("");
  return (
    <Store.Provider value={MyStore}>
      <div className="App">
        <MyComponent id={"someID"} />
      </div>
    </Store.Provider>
  );
}

const rootElement = document.getElementById("root");
render(<App />, rootElement);

MyComponent.tsx

import * as React from "react";
import { Observer } from "mobx-react-lite";
import { MyStore } from "./MyStore";

interface IProps {
  myStore?: MyStore;
  id: string;
}

export const Store = React.createContext();
const MyComponent: React.FC<IProps> = props => {
  const [state, setState] = React.useState("");
  const store = React.useContext(Store);
  console.log(state, store);
  return (
    <div>
      <h1>{props.id}</h1>
    </div>
  );
};
export default MyComponent;

작업 데모

참조URL: https://stackoverflow.com/questions/55330690/react-hooks-usestate-and-mobx-no-mobx-react-lite

반응형