我想用mobx把状态带到全局状态。我正努力在莫布克斯建立一个全球性的国家。另外,我想提到我正在使用mobx-react-lite库。
这是到代码框的链接。如果您打开这些命令,您将能够看到它在使用useState之前是如何工作的。https://codesandbox.io/s/mobx-react-lite-example-dfkm2y?file=/src/App.tsx
这是我的店
import { observable, action } from "mobx";
export class ProductStore {
@observable categories: string[] = [];
@action
addCategory = (val: string) => {
this.categories.push(val);
};
@action
removeCategory = (val: string) => {
this.categories = this.categories.filter((f) => f !== val);
};
}这是我的背景
import { createContext, useContext } from "react";
import { ProductStore } from "./productStore";
type ProductContextValue = {
productStore: ProductStore;
};
const ProductContext = createContext<ProductContextValue>(
{} as ProductContextValue
);
const productStore = new ProductStore();
export const ProductProvider: React.FC<React.PropsWithChildren<{}>> = ({
children
}) => {
return (
<ProductContext.Provider value={{ productStore }}>
{children}
</ProductContext.Provider>
);
};
export const useStore = () => useContext(ProductContext);我在组件中使用了、addCategory、和addCategory操作。当我进行调试时,我可以看到操作是正确的。
但是,我无法达到更新的类别。
以下是父组件
import "./styles.css";
import { ExampleComponent } from "./ExampleComponent";
import { useStore } from "./ProductContext";
import { useObserver } from "mobx-react-lite";
// import { useState } from "react";
export default function App() {
// const [selectedCategories, setSelectedCategories] = useState<string[]>([]);
const { productStore } = useStore();
return useObserver(() => (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
{/* old Version with useState */}
{/* {selectedCategories.map((m) => {
return <div>{m}</div>;
})} */}
{/* This section not working like a setState */}
{productStore.categories.map((m) => {
return <div>{m}</div>;
})}
<ExampleComponent
// selectedCategories={selectedCategories}
// setSelectedCategories={setSelectedCategories}
addCategory={productStore.addCategory}
removeCategory={productStore.removeCategory}
/>
</div>
));
}我怎样才能解决这个问题?我看不出mobx部分有什么变化。
发布于 2022-04-19 13:18:55
首先,您需要在存储构造函数中使用makeObservable,以使它现在与装饰器一起工作,如下所示:
import { observable, action, makeObservable } from 'mobx';
export class ProductStore {
@observable categories: string[] = [];
constructor() {
makeObservable(this);
}
@action
addCategory = (val: string) => {
this.categories.push(val);
};
@action
removeCategory = (val: string) => {
this.categories = this.categories.filter((f) => f !== val);
};
}其次,不要使用useObserver --这是不推荐的--使用<Observer>组件,或者用observer HOC包装整个组件。
https://stackoverflow.com/questions/71898259
复制相似问题