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

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

在我的 React 应用程序(使用打字稿)中,我想使用 React hooks(特别是 useState)来管理表单状态,同时将其用作 Mobx 存储的可观察组件,但我收到错误

Hooks can only be called inside the body of a function component.

例如在以下组件中

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 导出商店 class。是不是 Mobx 和 Hooks 的旧方法在哪里?

这里是 sanbox 的例子

mobx-react 不支持钩子,如果你想在 mobx 中使用钩子,你需要使用 mobx-react-lite which is also mentioned in the 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

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