在我的get应用程序(带有类型记录)中,我希望使用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的旧方法不是在哪里吗?
下面是示例的砂箱
发布于 2019-09-27 08:40:38
由于@Tholle提到了Mobx版本,现在Mobx 6已经发布,这个问题已经解决了
发布于 2019-03-25 06:30:01
mobx-react不支持钩子,如果您希望在mobx中使用钩子,则需要使用mobx-react-lite,这也是github文件中提到的
要做到这一点,您可以使用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;https://stackoverflow.com/questions/55330690
复制相似问题