【问题标题】:React Hooks (useState) and Mobx [No mobx-react-lite]React Hooks (useState) 和 Mobx [没有 mobx-react-lite]
【发布时间】:2019-08-15 06:35:27
【问题描述】:

在我的 react 应用程序(使用 typescript)中,我想使用 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 的例子

【问题讨论】:

  • mobx-react@5不支持钩子,但version 6 will support it, which is in rc.4 right now
  • @Tholle,谢谢。顺便说一句,我看到您在这里非常活跃,尤其是对于 react 标签,您是否认为自 16.8 以来使用上下文变得更加容易,为中小型应用程序构建自定义状态管理器是否更方便,而不是导入一些 MB 的库?
  • 你绝对可以使用例如useReducer 钩子并通过上下文共享状态对象和调度函数,这将适用于很多用例,但我认为它不会取代 MobX 用于中型应用程序。这在很大程度上取决于您的特定项目。

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


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    mobx-react 不支持 hooks,如果你想在 mobx 中使用 hooks,你需要使用 mobx-react-litegithub 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

    【讨论】:

      猜你喜欢
      • 2021-01-29
      • 2020-11-22
      • 2019-12-24
      • 2020-08-27
      • 1970-01-01
      • 1970-01-01
      • 2020-12-06
      • 2020-08-24
      • 2023-03-11
      相关资源
      最近更新 更多