如何使用MOBX,MOBX-REACT-LITE触发像SetState这样的状态?

发布于 2025-01-22 07:49:28 字数 2703 浏览 0 评论 0 原文

我想通过MOBX带入全球国家。我正在努力在MOBX创建一个全球状态。另外,我想提一下,我正在使用 mobx-react-lite 库。

这是指向CODESANBOX的链接。如果打开命令,您将能够在使用Usestate之前查看其工作原理。

这是我的商店

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 and removeCategory 在我的组件中的动作。当我进行调试时,我可以看到操作正常工作。

但是,我无法达到更新的类别

这是父组件

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部分的任何更改。

I want to carry to states into the global state with mobx. I'm struggling to create a global state in mobx. Also, I would like to mention that I'm using mobx-react-lite library.

Here is the link to codesanbox. If you open the commands, you will be able to see how it works before with useState. https://codesandbox.io/s/mobx-react-lite-example-dfkm2y?file=/src/App.tsx

This is my store

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);
  };
}

Here is my context

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);

I use addCategory and removeCategory action in my component. When I'm doing debugging, I can see that actions work correctly.

However, I can not reach the categories of updates.

Here is the parent component

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>
  ));
}

How Can I fix this problem? I can not see any changes in the mobx section.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

只为守护你 2025-01-29 07:49:28

首先,您需要使用 MakeObServable 在商店构造函数中以使其与Decorator一起使用,例如:

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);
  };
}

第二,请勿使用 Usebserver 它已弃用,请使用&lt; observer&gt; 组件或用观察者 hoc包装整个组件。

First of all you need to use makeObservable inside store constructor to make it work with decorators now, like that:

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);
  };
}

And second, don't use useObserver it's deprecated, use <Observer> component or wrap entire component with observer HOC.

Working Codesandbox

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文