React Hooks(useState)和Mobx [No mobx-react-lite]

时间:2019-03-25 02:53:58

标签: reactjs mobx mobx-react react-hooks react-tsx

在我的React应用程序(带有打字稿)中,我想使用React钩子(特别是useState)来管理表单状态,同时将其用作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

2 个答案:

答案 0 :(得分:3)

感谢@Tholle提到了Mobx版本,现在Mobx 6已发布,此问题已解决

答案 1 :(得分:2)

mobx-react不支持钩子,如果您希望将钩子与mobx一起使用,则需要使用mobx-react-lite

中也提到的github documentation

为此,您可以使用React.createContext代替提供者,使用useContext代替inject

Index.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;

Working demo