In JavaScript, state management is a hot of discussion these days. When it comes to implementing state management, developers often find it challenging dealing with boilerplate code in Redux. Hence, MobX has proved to be a good alternative to Redux which gives the same functionality with less code to write. However, both state management tools work well with React.
在JavaScript中,状态管理已成为当今讨论的热点。 在实施状态管理时,开发人员经常发现在Redux中处理样板代码具有挑战性。 因此,事实证明,MobX是Redux的一个很好的替代品,它以更少的代码提供了相同的功能。 但是,两个状态管理工具都可以与React一起很好地工作。
1) Both support time-travel debugging
1)都支持时间旅行调试
2) Both contain open-source libraries
2)两者都包含开源库
3) Both provide a client-side state management
3)两者都提供客户端状态管理
4) Both provide huge support for React native frameworks
4)两者都为React本机框架提供了巨大的支持
In this blog, we have listed all the pros and cons of both state management solutions. It will help web developers to choose the best one for their next project. Before discussing this, we have compared both Redux and Mobx based on some parameters as given below:
在此博客中,我们列出了两种状态管理解决方案的优点和缺点。 它将帮助网络开发人员为他们的下一个项目选择最佳的解决方案。 在讨论这一点之前,我们根据以下给出的一些参数比较了Redux和Mobx:
-> Maintenance & Scalable
->维护和可扩展
Due to the presence of pure functions & functional programming paradigm, Redux is more scalable & maintainable. Hence, things cab be easily controlled with Redux.
由于纯函数和函数式编程范例的存在,Redux更具可伸缩性和可维护性。 因此,可以使用Redux轻松控制事物。
-> Debug process
->调试过程
Debugging in Redux is a good experience as compared to MobX as it provides awesome developer tools and comes with less abstraction. With the flux paradigm, the Redux becomes more predictable. On the other hand, due to more abstraction and average developer tools, debugging in MobX is a lot harder.
与MobX相比,在Redux中进行调试是一个很好的体验,因为它提供了很棒的开发人员工具,并且抽象程度较低。 借助通量范例,Redux变得更加可预测。 另一方面,由于更多的抽象和普通的开发人员工具,MobX中的调试要困难得多。
-> Learning curve
->学习曲线
To learn MobX is easy as it comes with a steady learning curve. The presence of maximum abstraction makes it easy to learn and JavaScript developers familiar with OOP concepts have a stronghold on MobX. On the other hand, Redux uses a functional programming paradigm which makes it hard to grasp in straightway.
学习MobX很容易,因为它具有稳定的学习曲线。 最大抽象的存在使学习变得容易,并且熟悉OOP概念JavaScript开发人员在MobX上拥有据点。 另一方面,Redux使用功能性编程范例,这使它难以一目了然。
-> Community
->社区
Redux has a large community base as compared to MobX. Hence, Redux provides great community support to developers anytime at any place.
与MobX相比,Redux具有庞大的社区基础。 因此,Redux可以随时随地为开发人员提供强大的社区支持。
-> Impure vs pure
->不纯与纯
MobX is impure as the states can be overwritten. Here, you can easily update states with the new values. However, Redux is pure as it uses pure functions. Here, the states are read-only and it cannot be directly overwritten. The previous state gets replaced with a new state.
MobX不纯,因为状态可以被覆盖。 在这里,您可以轻松地使用新值更新状态。 但是,Redux是纯函数,因为它使用纯函数。 在这里,状态是只读的,不能直接覆盖。 之前的状态被替换为新的状态。
-> Observable vs plain data
->可观察与纯数据
MobX uses an observable to store while Redux uses normal Javascript data to store values. In Redux, all updates are tracked manually.
MobX使用可观察的存储,而Redux使用普通的Javascript数据存储值。 在Redux中,所有更新都是手动跟踪的。
-> Store
->商店
A store is something where data is placed. MobX has more than one store where these stores are logically separated. On the other hand, Redux has one large store where all states are stored. The data is usually normalized in Redux and data is kept denormalized in MobX.
商店是放置数据的地方。 MobX有多个商店,这些商店在逻辑上是分开的。 另一方面,Redux有一个存储所有状态的大型存储。 通常在Redux中将数据标准化,而在MobX中将数据保持非标准化状态。
React-redux’s connect() function is used to pass state and actions to props in Redux. It is shown below:
React-redux的connect()函数用于将状态和操作传递给Redux中的prop。 如下图所示:
// accessing props
//访问道具
// function for injecting state into props
//将状态注入道具的函数
function mapStateToProps(state) {
return {
contact: state.contactStore.contact,
errors: state.contactStore.errors
}
}
// injecting both state and actions into props
//将状态和动作都注入道具
export default connect(mapStateToProps, { newContact,
saveContact,
fetchContact,
updateContact
})(ContactFormPage);
In MobX, inject is used to inject the stores' collection. This will make stores available in props. Here, state and actions are accessed via properties in the store object so no need to pass them separately.
在MobX中, 注入用于注入商店的集合。 这将使商店在道具中可用。 在这里,状态和动作是通过store对象中的属性访问的,因此无需分别传递它们。
@inject("stores") @observer // injecting store into props
class ContactFormPage extends Component {
…
// accessing store via props
const { contactStore:store } = this.props.stores;
return (
)
…
}
Hence, we used redux-connect-decorators to simplify the Redux code and the MobX version is always easy to read. Hence, no such clear winner.
因此,我们使用redux-connect-decorators简化了Redux代码,并且MobX版本始终易于阅读。 因此,没有这样明确的赢家。
In Redux, first, define store and App is passed via Provider. To handle asynchronous functions, you also need to define redux-thunk and redux-promise-middleware. After this, redux-devtools-extension allow debugging store in time-traveling mode.
在Redux中,首先定义定义商店,然后通过Provider传递应用。 要处理异步功能,您还需要定义redux-thunk和redux-promise-middleware。 此后,redux-devtools-extension允许在时间旅行模式下调试存储。
import { applyMiddleware, createStore } from "redux";
import thunk from "redux-thunk";
import promise from "redux-promise-middleware";
import { composeWithDevTools } from 'redux-devtools-extension';
import rootReducer from "./reducers";
const middleware = composeWithDevTools(applyMiddleware(promise(), thunk));
export default createStore(rootReducer, middleware);
// src/index.js
// src / index.js
ReactDOM.render(
,
document.getElementById('root')
);
In MobX, multiple stores are set up. It does not need external libraries to handle async actions but only a few lines of code. You need the mobx-remotedev for connecting redux-devtools-extension debugging tool.
在MobX中,设置了多个商店。 它不需要外部库来处理异步操作,而只需几行代码。 您需要mobx-remotedev来连接redux-devtools-extension调试工具。
import remotedev from 'mobx-remotedev';
import Store from './store';
const contactConfig = {
name:'Contact Store',
global: true,
onlyActions:true,
filters: {
whitelist: /fetch|update|create|Event|entity|entities|handleErrors/
}
};
const contactStore = new Store('api/contacts');
const allStores = {
contactStore: remotedev(contactStore, contactConfig)
};
export default allStores;
// src/index.js
// src / index.js
ReactDOM.render(
,
document.getElementById('root')
);
The amount of code used in both is however same. But, MobX contains fewer import statements.
但是,两者中使用的代码量相同。 但是,MobX包含的导入语句更少。
Actions & reducers are defined in Redux by following code:
通过以下代码在Redux中定义了动作和缩减器:
// actions
//动作
export function fetchContacts(){
return dispatch => {
dispatch({
type: 'FETCH_CONTACTS',
payload: client.get(url)
})
}
}
// reducers
//减速器
switch (action.type) {
case 'FETCH_CONTACTS_FULFILLED': {
return {
...state,
contacts: action.payload.data.data || action.payload.data,
loading: false,
errors: {}
}
}
case 'FETCH_CONTACTS_PENDING': {
return {
...state,
loading: true,
errors: {}
}
}
case 'FETCH_CONTACTS_REJECTED': {
return {
...state,
loading: false,
errors: { global: action.payload.message }
}
}
}
The logic for action & reducer is done in one class in MobX. It uses OOP due to which the Store class is refactored to create multiple stores using the class constructor. The respective code is shown below:
动作和减速器的逻辑是在MobX中的一类中完成的。 由于使用OOP,Store类被重构以使用类构造函数创建多个商店。 相应的代码如下所示:
@action
fetchAll = async() => {
this.loading = true;
this.errors = {};
try {
const response = await this.service.find({})
runInAction('entities fetched', () => {
this.entities = response.data;
this.loading = false;
});
} catch(err) {
this.handleErrors(err);
}
}
So, we have seen that the logic defined in both state management solutions do the same job. The only difference is that we have used 33 lines of code in Redux and 14 lines of code in MobX to achieve the result. Hence, you can build apps faster with MobX.
因此,我们已经看到,两种状态管理解决方案中定义的逻辑都可以完成相同的工作。 唯一的不同是,我们在Redux中使用了33行代码,在MobX中使用了14行代码来实现结果。 因此,您可以使用MobX更快地构建应用程序。
MobX is a tested library that makes state management simple & scalable by applying functional reactive programming (TFRP) transparently. React and MobX is a powerful combination together.
MobX是经过测试的库,可通过透明地应用功能React式编程(TFRP)使状态管理变得简单且可扩展。 React和MobX是强大的组合。
Redux is a standalone library that can be used with UI framework including Angular, Vue, Ember, React & vanilla JS.
Redux是一个独立的库,可以与UI框架一起使用,包括Angular,Vue,Ember,React和vanilla JS。
Now, you can see that the MobX code base is much more agile. Using OOP style and good development practices, you can quickly create React applications. The main disadvantage is that it is very easy to write poor code and impossible to maintain.
现在,您可以看到MobX代码库更加敏捷。 使用OOP风格和良好的开发实践,您可以快速创建React应用程序。 主要缺点在于,编写不良代码非常容易,并且无法维护。
On the other hand, Redux is popular one and suitable for building large & complex projects. It is a strict framework with safeguards that ensures that each developer writes code that is easy to test and maintain. However, it is not suitable for small projects.
另一方面,Redux很受欢迎,适合于构建大型和复杂的项目。 这是一个带有防护措施的严格框架,可确保每个开发人员编写易于测试和维护的代码。 但是,它不适合小型项目。
I hope I have provided enough information to clarify whether to migrate to MobX or continue with Redux. Ultimately, the decision depends on the type of project you are working on and the resources available to you.
我希望我提供了足够的信息来阐明是迁移到MobX还是继续使用Redux。 最终,决定取决于您正在处理的项目类型和可用资源。
翻译自: https://habr.com/en/post/480692/