像Redux这样的Mobx项目结构 [英] Structure Mobx project like Redux

查看:71
本文介绍了像Redux这样的Mobx项目结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将mobx项目构建为看起来像redux项目.将配置存储在一个文件中,将操作存储在另一个文件中,也许将其他一些逻辑和反应存储在第三个文件中.

I would like to structure mobx project to look like redux project. Store configuration in one file, actions in another file, maybe some other logic and reactions in third file.

还有,最佳实践是什么?有一家像redux或更多的商店.我该怎么做(从一个类内部取出@action并从另一个文件中分派它).有人可以给出一些很好的例子来构造他们的项目吗?

Also, what is the best practice? To have one store like redux or more. How would I do that (taking out @action from inside a class and dispatching it from another file). Can anybody give some nice examples of structuring their projects?

推荐答案

装饰器(@)是将MobX与类一起使用的一种好方法,但是您可以完全不使用它们而使用MobX.

Decorators (@) are a nice way to use MobX with classes, but you can use MobX without using them at all.

您可以使用action的功能版本来构建应用程序,如下所示:

You could structure your application like this, by using the function version of action:

示例( JSBin )

Example (JSBin)

// state.js
useStrict(true);

const appState = observable({
  count: 0,
  firstName: 'Igor',
  lastName: 'Vuk',
  fullName: computed(function() {
    return `${this.firstName}-${this.lastName}`;
  })
});

// actions.js
const increment = action(function() {
  ++appState.count;
});

const changeLastName = action(function() {
  appState.lastName = 'Stravinskij';
});

// app.js
autorun(() => {
  console.log(`${appState.fullName} has been logged in for ${appState.count} seconds`);
});

setInterval(() => {
  increment();
}, 1000);

setTimeout(() => {
  changeLastName();
}, 3000)

这篇关于像Redux这样的Mobx项目结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆