简体   繁体   English

如何在 Create-React-App 中实现 MobX?

[英]How to implement MobX in Create-React-App?

While studying React, and Redux, I was told to have a look at MobX as well, because it's much simpler.在学习 React 和 Redux 时,有人告诉我也可以看看 MobX,因为它简单得多。 And I agree, I find it more intuitive when demonstrated to me.我同意,当向我展示时,我发现它更直观。 But when I try to implement it in my React project I run into a lot of trouble, eg with the decorators, experimental syntax warnings and when fixed I run into a lot of more trouble.但是当我尝试在我的 React 项目中实现它时,我遇到了很多麻烦,例如装饰器、实验性语法警告以及修复后我遇到了更多的麻烦。 And I can't follow tutorials, it does not look the same to me when I try it, new versions have arrived since then, etc..而且我无法遵循教程,当我尝试它时,它看起来与我不一样,从那时起新版本已经到来,等等。

After installing:安装后:

npm install mobx --save
npm install mobx-react --save

...what confuses me is the usage of the 2 files for further settings (or do I need just one of them?): ...让我感到困惑的是使用这 2 个文件进行进一步设置(或者我只需要其中一个?):

.babelrc
babel.config.js

Do I have to create those files myself (or just one of them)?, and WHERE??我是否必须自己创建这些文件(或只是其中之一)?,以及在哪里?

And I am also told by tutorials to change babel section in package.json, but there is no such section.而且教程还告诉我要更改 package.json 中的 babel 部分,但没有这样的部分。 Right now I am stuck in a compiler (VSCode) error:现在我陷入了编译器(VSCode)错误:

"Support for the experimental syntax ‘decorators-legacy’ isn’t currently enabled".

I did run the command:我确实运行了命令:

npm install @babel/plugin-proposal-decorators  

.. but there is still that error when compiling in VSCode. .. 但在 VSCode 中编译时仍然存在该错误。

In MobX 6 there is a new thing that will probably allow you to drop decorators altogether, makeAutoObservable :在 MobX 6 中,有一个新东西可能会让你完全删除装饰器, makeAutoObservable

import { makeAutoObservable } from "mobx"

class Store {
  // Don't need decorators now
  string = 'Test String';

  setString = (string) => {
    this.string = string;
  };

  constructor() {
    // Just call it here
    makeAutoObservable (this);
  }
}

With that you don't even need decorator syntax to be enabled.有了它,您甚至不需要启用装饰器语法。

More info here https://mobx.js.org/migrating-from-4-or-5.html and https://mobx.js.org/react-integration.html更多信息在这里https://mobx.js.org/migrating-from-4-or-5.htmlhttps://mobx.js.org/react-integration.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM