Home  >  Article  >  Web Front-end  >  Detailed explanation of selection examples of Redux and Mobx

Detailed explanation of selection examples of Redux and Mobx

小云云
小云云Original
2018-02-09 13:17:281403browse

Redux and Mobx are both popular data flow models at the moment. It seems that the community is naturally confused about what to choose to replace Redux. The developer is not sure which solution to choose. This problem is not limited to Redux and Mobx. Whenever there is a choice, people are curious about what is the best way to solve a problem. What I am writing now is to resolve the confusion between the two state management libraries Redux and Mobx.

Most articles use React to introduce the usage of Mobx and Redux. But in most cases you can replace React with Angular, Vue, or something else.

In early 2016 I wrote a fairly large application using React + Redux. When I discovered that Mobx could be used as an alternative to Redux, I took the time to refactor the application from Redux to Mobx. Now I can use them very comfortably and explain their usage.

What is this article going to talk about? If you don't plan to read such a long article (TLDR: too long, didn't read (please bring your own ladder to view this link)), you can look at the table of contents. But I want to give you more details: First, I want to briefly review what problems the state management library solves for us. After all, we can do just as well if we only use setState() when writing React or use setState() and similar methods when writing other SPA frameworks. Second, I will briefly talk about the similarities and differences between them. Third, I will show beginners in the React ecosystem how to learn React’s state management. Friendly reminder: before you dive into Mobx and Redux, please use setState() first. Finally, if you already have an application using Mobx or Redux, I'll give you more of my understanding on how to refactor from one of the state management libraries to the other.

Contents

What problem are we trying to solve?

What is the difference between Mobx and Redux?

The learning curve of React state management

Try another state management solution?

Final Thoughts

What problem are we trying to solve?

Everyone wants to use state management in their applications. But what problem does it solve for us? Many people have introduced a state management library when starting a small application. Everyone is talking about Mobx and Redux, right? But most applications don't need large-scale state management in the beginning. This can even be dangerous because these people will not be able to experience the problems that libraries like Mobx and Redux are meant to solve.

The current situation is to use components to build a front-end application. Components have their own internal state. For example, in React, the above-mentioned local state is handled using this.state and setState(). But state management of local state can quickly become confusing in a bloated application because:

One component needs to share state with another component

One component needs When the state of another component is changed to a certain extent, it will become increasingly difficult to deduce the state of the application. It becomes a confusing application with many state objects modifying each other's state at the component level. In most cases, state objects and state modifications do not need to be bound to some component. When you promote states, they are available through the component tree.

So, the solution is to introduce a state management library, such as Mobx or Redux. It provides tools to save state, modify state and update state somewhere. You can get the state from one place, modify it from one place, and get its updates from one place. It follows the single source of data principle. This makes it easier for us to infer state values ​​and state modifications because they are decoupled from our components.

State management libraries like Redux and Mobx generally have accompanying tools, such as react-redux and mobx-react used in React, which enable your components to obtain state. Typically, these components are called container components, or more specifically, connected components. As long as you upgrade your component to a connected component, you can get and change state anywhere in the component hierarchy.


What is the difference between Mobx and Redux?

Before we dive into the differences between Redux and Mobx, I want to talk about the similarities between them.

Both libraries are used to manage the state of JavaScript applications. They don’t have to be bundled with React, they can also be used with other libraries like AngularJs and VueJs. But they integrate very well with the ideas of React.

If you choose one of these state management solutions, you won't feel locked in. Because you can switch to another solution at any time. You can switch from Mobx to Redux or from Redux to Mobx. I'll show you how to do this below.

Dan Abramov's Redux is derived from the flux architecture. Different from flux, Redux uses a single store instead of multiple stores to save state. In addition, it uses pure functions instead of dispatchers to modify state. If you are not familiar with flux and have not been exposed to state management, don’t be fooled by this content. trouble.

Redux is influenced by FP (Functional Programming) principles. FP can be used in JavaScript, but many people have a background in object-oriented languages, such as Java. They have a hard time adapting to the principles of functional programming at first. This is why Mobx may be simpler for beginners.

Since Redux embraces FP, it uses pure functions. A pure function that takes input and returns output and has no other dependencies. A pure function always has the same output given the same inputs and has no side effects.


(state, action) => newState

Your Redux state is immutable, you should always return a new state rather than modify the original state. You should not perform state modifications or changes based on object references.


// don't do this in Redux, because it mutates the array
function addAuthor(state, action) {
 return state.authors.push(action.author);
}
// stay immutable and always return a new object
function addAuthor(state, action) {
 return [ ...state.authors, action.author ];
}

Finally, in the idiom of Redux, the format of state is standardized like a database. Entities refer to each other only by id, which is a best practice. Although not everyone does this, you can also use normalizr to normalize the state. Normalized state allows you to maintain a flat state and keep entities as a single source of data.


{
 post: {
 id: 'a',
 authorId: 'b',
 ...
 },
 author: {
 id: 'b',
 postIds: ['a', ...],
 ...
 }
}

Michel Weststrate's Mobx is influenced by object-oriented programming and reactive programming. It wraps state into an observable object, so your state has all the capabilities of Observable. The state data can only have ordinary setters and getters, but observable allows us to get updated values ​​when the data changes.

The state of Mobx is mutable, so you modify the state directly:


##

function addAuthor(author) {
 this.authors.push(author);
}

Other than that, the state entity remains nested data structures to relate to each other. You don't have to standardize the state, instead keep them nested.


{
 post: {
 id: 'a',
 ...
 author: {
 id: 'b',
 ...
 }
 }
}

Single store vs. multiple stores

In Redux, you put all the state in a global store. This store object is your single data source. On the other hand, multiple reducers allow you to modify immutable state.


Mobx, on the other hand, uses multiple stores. Similar to Redux reducers, you can divide and conquer at a technical level or domain. Maybe you want to store your domain entities in different stores but still maintain control of the state in the view. After all, you configure state to make your application look reasonable.


Technically speaking, you can also use multiple stores in Redux. No one forces you to use only one store. But that's not the recommended usage of Redux. Because that goes against best practices. In Redux, your single store responds to updates through global events on reducers.


how to use?

You need to follow the code below to learn to use Redux. First, add a user array to the global state. You can see that I'm using the object spread operator to return a new object. You can also use Object.assign() in ES6 (originally ES5, actually ES6) to operate on immutable objects.


const initialState = {
 users: [
 {
 name: 'Dan'
 },
 {
 name: 'Michel'
 }
 ]
};
// reducer
function users(state = initialState, action) {
 switch (action.type) {
 case 'USER_ADD':
 return { ...state, users: [ ...state.users, action.user ] };
 default:
 return state;
 }
}
// action
{ type: 'USER_ADD', user: user };

You must use dispatch({ type: 'USER_ADD', user: user }); to add a new user to the global state.


In Mobx, a store only manages one sub-state (just like the reducer that manages sub-state in Redux), but you can modify the state directly.

@observable allows us to observe changes in state.


class UserStore {
 @observable users = [
 {
 name: 'Dan'
 },
 {
 name: 'Michel'
 }
 ];
}

Now we can call the method of the store instance: userStore.users.push(user);. This is a best practice, although using actions to modify state is more explicit.


class UserStore {
 @observable users = [
 {
 name: 'Dan'
 },
 {
 name: 'Michel'
 }
 ];
 @action addUser = (user) => {
 this.users.push(user);
 }
}

In Mobx you can add useStrict() to force the use of action. Now you can call the method on the store instance: userStore.addUser(user); to modify your state.


You've seen how to update state in Redux and Mobx. They are different. The state in Redux is read-only. You can only use explicit actions to modify the state. In Mobx, on the contrary, the state is readable and writable. You can modify the state directly without using actions, but you can useStrict( ) to use explicit actions.


Learning Curve of React State Management

React applications make extensive use of Redux and Mobx. But they are independent state management libraries and can be used anywhere except React. Their interop library allows us to easily connect React components. react-redux for Redux + React and mobx-react for MobX + React. I'll explain how they are used in the React component tree later.


In recent discussions, people have been debating the learning curve of Redux. This usually happens in the following scenario: React beginners who want to use Redux for state management. Most people think that React and Redux have high learning curves on their own, and that combining the two can get out of hand. An alternative is Mobx as it is more suitable for beginners.


然而,我会建议 React 的初学者一个学习状态管理的新方法。先学习React 组件内部的状态管理功能。在 React 应用,你首先会学到生命周期方法,而且你会用 setState() 和 this.state 解决本地的状态管理。我非常推荐上面的学习路径。不然你会在 React 的生态中迷失。在这条学习路径的最后,你会认识到组件内部管理状态难度越来越大。毕竟那是 The Road to learn React 书里如何教授 React 状态管理的方法。

现在我们重点讨论 Redux 和 Mobx 为我们解决了什么问题?它俩都提供了在组件外部管理应用状态的方法。state 与组件相互解耦,组件可以读取 state ,修改 state ,有新 state 时更新。这个 state 是单一数据源。

现在你需要选择其中一个状态管理库。这肯定是要第一时间解决的问题。此外,在开发过相当大的应用之后,你应该能很自如使用 React 。

初学者用 Redux 还是 Mobx ?

一旦你对 React 组件和它内部的状态管理熟悉了,你就能选择出一个状态管理库来解决你的问题。在我两个库都用过后,我想说 Mobx 更适合初学者。我们刚才已经看到 Mobx 只要更少的代码,甚至它可以用一些我们现在还不知道的魔法注解。
用 Mobx 你不需要熟悉函数式编程。像“不可变”之类的术语对你可能依然陌生。函数式编程是不断上升的范式,但对于大部分 JavaScript 开发者来说是新奇的。虽然它有清晰的趋势,但并非所有人都有函数式编程的背景,有面向对象背景的开发者可能会更加容易适应 Mobx 的原则。

   注:Mobx 可以很好的在 React 内部组件状态管理中代替 setState,我还是建议继续使用 setState() 管理内部状态。但链接文章很清楚的说明了在 React 中用 Mobx 完成内部状态管理是很容易的。                                                                      

规模持续增长的应用

在 Mobx 中你改变注解过的对象,组件就会更新。Mobx 比 Redux 使用了更多的内部魔法实现,因此在刚开始的时候只要更少的代码。有 Angular 背景的会觉得跟双向绑定很像。你在一个地方保存 state ,通过注解观察 state ,一旦 state 修改组件会自动的更新。

Mobx 允许直接在组件树上直接修改 state 。


// component
<button onClick={() => store.users.push(user)} />

更好的方式是用 store 的 @action 。


// component
<button onClick={() => store.addUser(user)} />
// store
@action addUser = (user) => {
 this.users.push(user);
}

用 actions 修改 state 更加明确。上面也提到过,有个小功能可以强制的使用 actions 修改 state 。


// root file
import { useStrict } from &#39;mobx&#39;;
useStrict(true);

这样的话第一个例子中直接修改 store 中的 state 就不再起作用了。前面的例子展示了怎样拥抱 Mobx 的最佳实践。此外,一旦你只用 actions ,你就已经使用了 Redux 的约束。

在快速启动一个项目时,我会推荐使用 Mobx ,一旦应用开始变得越来越大,越来越多的人开发时,遵循最佳实践就很有意义,如使用明确的 actions 。这是拥抱 Redux 的约束:你永远不能直接修改 state ,只能使用 actions 。

迁移到 Redux

一旦应用开始变得越来越大,越来越多的人开发时,你应该考虑使用 Redux 。它本身强制使用明确的 actions 修改 state 。action 有 type 和 payload 参数,reducer 可以用来修改 state 。这样的话,一个团队里的开发人员可以很简单的推断 state 的修改。


// reducer
(state, action) => newState

Redux 提供状态管理的整个架构,并有清晰的约束规则。这是 Redux 的成功故事。

另一个 Redux 的优势是在服务端使用。因为我们使用的是纯 JavaScript ,它可以在网络上传输 state 。序列化和反序列化一个 state 对象是直接可用的。当然 Mobx 也是一样可以的。

Mobx 是无主张的,但你可以通过 useStrict() 像 Redux 一样使用清晰的约束规则。这就是我为什么没说你不能在扩张的应用中使用 Mobx ,但 Redux 是有明确的使用方式的。而 Mobx 甚至在文档中说:“ Mobx 不会告诉你如何组织代码,哪里该存储 state 或 怎么处理事件。”所以开发团队首先要确定 state 的管理架构。

状态管理的学习曲线并不是很陡峭。我们总结下建议:React 初学者首先学习恰当的使用 setState() 和 this.state 。一段时间之后你将会意识到在 React 应用中仅仅使用 setState() 管理状态的问题。当你寻找解决方案时,你会在状态管理库 Mobx 或 Redux 的选择上犹豫。应该选哪个呢?由于 Mobx 是无主张的,使用上可以和 setState() 类似,我建议在小项目中尝试。一旦应用开始变得越来越大,越来越多的人开发时,你应该考虑在 Mobx 上实行更多的限制条件或尝试使用 Redux 。我使用两个库都很享受。即使你最后两个都没使用,了解到状态管理的另一种方式也是有意义的。

尝试另一个状态管理方案?

你可能已经使用了其中一个状态管理方案,但是想考虑另一个?你可以比较现实中的 Mobx 和 Redux 应用。我把所有的文件修改都提交到了一个Pull Request 。在这个 PR 里,项目从 Redux 重构成了 Mobx ,反之亦然,你可以自己实现。我不认为有必要和 Redux 或 Mobx 耦合,因为大部分的改变是和其他任何东西解耦的。

你主要需要将 Redux 的 Actions、Action Creator、 Action Types、Reducer、Global Store 替换成 Mobx 的 Stores 。另外将和 React 组件连接的接口 react-redux 换成 mobx-react 。presenter + container pattern 依然可以执行。你仅仅还要重构容器组件。在 Mobx 中可以使用 inject 获得 store 依赖。然后 store 可以传递 substate 和 actions 给组件。Mobx 的 observer 确保组件在 store 中 observable 的属性变化时更新。


import { observer, inject } from &#39;mobx-react&#39;;
...
const UserProfileContainer = inject(
 &#39;userStore&#39;
)(observer(({
 id,
 userStore,
}) => {
 return (
 <UserProfile
 user={userStore.getUser(id)}
 onUpdateUser={userStore.updateUser}
 />
 );
}));

Redux 的话,你使用 mapStateToProps 和 mapDispatchToProps 传递 substate 和 actions 给组件。


import { connect } from &#39;react-redux&#39;;
import { bindActionCreators } from &#39;redux&#39;;
...
function mapStateToProps(state, props) {
 const { id } = props;
 const user = state.users[id];
 return {
 user,
 };
}
function mapDispatchToProps(dispatch) {
 return {
 onUpdateUser: bindActionCreators(actions.updateUser, dispatch),
 };
}
const UserProfileContainer = connect(mapStateToProps, mapDispatchToProps)(UserProfile);

这有一篇怎样将 Redux 重构为 Mobx指南。但就像我上面说过的,反过来一样也是可以的。一旦你选择了一个状态管理库,你会知道那并没有什么限制。它们基本上是和你的应用解耦的,所以是可以替换的。

最后思考

每当我看 Redux vs Mobx 争论下的评论时,总会有下面这条:“Redux 有太多的样板代码,你应该使用 Mobx,可以减少 xxx 行代码”。这条评论也许是对的,但没人考虑得失,Redux 比 Mobx 更多的样板代码,是因为特定的设计约束。它允许你推断应用状态即使应用规模很大。所以围绕 state 的仪式都是有原因的。

Redux 库非常小,大部分时间你都是在处理纯 JavaScript 对象和数组。它比 Mobx 更接近 vanilla JavaScript 。Mobx 通过包装对象和数组为可观察对象,从而隐藏了大部分的样板代码。它是建立在隐藏抽象之上的。感觉像是出现了魔法,但却很难理解其内在的机制。Redux 则可以简单通过纯 JavaScript 来推断。它使你的应用更简单的测试和调试。
另外,我们重新回到单页应用的最开始来考虑,一系列的单页应用框架和库面临着相同的状态管理问题,它最终被 flux 模式解决了。Redux 是这个模式的成功者。

Mobx 则又处在相反的方向。我们直接修改 state 而没有拥抱函数式编程的好处。对一些开发者来说,这让他们觉得像双向绑定。一段时间之后,由于没有引入类似 Redux 的状态管理库,他们可能又会陷入同样的问题。状态管理分散在各个组件,导致最后一团糟。

使用 Redux,你有一个既定的模式组织代码,而 Mobx 则无主张。但拥抱 Mobx 最佳实践会是明智的。 开发者需要知道如何组织状态管理从而更好的推断它。不然他们就会想要直接在组件中修改它。

两个库都非常棒。Redux 已经非常完善,Mobx 则逐渐成为一个有效的替代。

相关推荐:

react-redux中connect的装饰器用法

如何理解 redux

在React中使用Redux的实例详解

The above is the detailed content of Detailed explanation of selection examples of Redux and Mobx. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn