In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "what is MobX". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what is MobX".
Extraneous remarks
Before introducing the use of MobX, let's say something beside the point. We can take a look at the brief introduction of MobX in Chinese. On MobX's Chinese website, it reads:
MobX is a war-baptized library that makes state management simple and extensible through transparent functional responsive programming.
Data stream
"the Library of War Baptism" feels strange and mouthful to read, and many online articles about MobX are written in this way. I read its README in github and found that it was written as follows:
"MobX is a battle tested library that makes state management simple and scalable by transparently applying functional reactive programming (TFRP).
It can be seen that what the author originally intended to express is that MobX has undergone a lot of tests and has a strong robustness. Here are the results translated by Google, which also seems to be more accurate than the expression on the Chinese website.
Google translate
Although my English level is also very poor, I will try my best to read the official documents so as to avoid some unnecessary misunderstandings.
How to use it?
Back to the point, the latest version of MobX is 6.0. this version of API is much simpler than before and can be said to be easier to use. Previous versions were decorator-style syntax candy, but decorators are not mature in the current ES specification, and the introduction of decorator syntax increases the size of packaged code. After comprehensive consideration, MobX 6. 0 cancels the API of decorator syntax.
Responsive object
MobX uses the makeObservable method to construct responsive objects, and the object properties passed in are proxied by Proxy, similar to Vue, which used Object.defineProperty API before version 6. 0, of course, 6. 0 also provides a degradation scheme.
Import {configure, makeObservable, observable, action, computed} from 'mobx' / / using this configuration, you can downgrade Proxy to Object.defineProperty configure ({useProxies: "never"}) / / construct response objects const store = makeObservable (/ / response objects that need to be proxied {count: 0, get double () {return this.count * 2}, increment () {this.count + = 1}, decrement () {this.count-= 1}}, / / wrap each attribute The response attribute that is used to mark the role of this attribute {count: observable, / / response attribute to be tracked: double: computed, / / calculation attribute increment: action, / / action is called, the response object decrement: action, / / action is modified})
Let's take a look at the previous version of MobX, written using a decorator:
Class Store {@ observable count = 0 constructor () {makeObservable (this)} @ action increment () {this.count++;} @ action decrement () {this.count--;} @ computed get double () {return this.count * 2}} const store = new Store ()
In this way, it seems that the writing method has not been simplified, as if it is a little more complicated than writing decorators. Let's take a look at version 6. 0, a more powerful API:makeAutoObservable.
MakeAutoObservable is a more powerful makeObservable that automatically adds object wrapper functions to attributes, resulting in a plummeting cost.
Import {makeAutoObservable} from 'mobx' const store = makeAutoObservable ({count: 0, get double () {return this.count * 2}, increment () {this.count + = 1}, decrement () {this.count-= 1}})
Calculation attribute
The property of MobX is the same as the computed of Vue, in makeAutoObservable, it is a value that getter,getter depends on. Once the value of getter changes, so does the return value of getter itself.
Import {makeAutoObservable} from 'mobx' const store = makeAutoObservable ({count: 0, get double () {return this.count * 2}})
When store.count is 1, calling store.double returns 2.
Modify behavior
When we need to modify the response property on store, we can modify it by directly reassigning the value, but we will get a warning from MobX.
Const store = makeAutoObservable ({count: 0}); document.getElementById ("increment"). Onclick = function () {store.count + = 1}
Warn
MobX prompts that when you modify the properties of a responsive object, you need to modify it in an action way. Although direct modification can also take effect, it will confuse the management of MobX state, and putting state modification into action allows MobX to modify it in the internal transaction process, so as to avoid getting an attribute in the intermediate state, and the final calculation result is not accurate enough.
All methods in makeAutoObservable are processed as action.
Import {makeAutoObservable} from 'mobx' const store = makeAutoObservable ({count: 0, get double () {return this.count * 2}, increment () {/ / action this.count + = 1}, decrement () {/ / action this.count-= 1}})
Unlike Vuex, state modification is divided into mutation and action, synchronous modification is placed in mutation, and asynchronous operations are placed in action. In MobX, both synchronous and asynchronous operations can be put into action, but asynchronous operations need to put assignment operations into runInAction when modifying properties.
Import {runInAction, makeAutoObservable} from 'mobx' const store = makeAutoObservable ({count: 0, async initCount () {/ / simulate getting remote data const count = await new Promise ((resolve) = > {setTimeout (()) = > {resolve (10)}, 500)}) / / after obtaining the data Put the assignment operation in runInAction runInAction (() = > {this.count = count})}}) store.initCount ()
If you do not call runInAction, you can directly call the action that already exists.
Import {runInAction, makeAutoObservable} from 'mobx' const store = makeAutoObservable ({count: 0, setCount (count) {this.count = count}, async initCount () {/ / simulate obtaining remote data const count = await new Promise ((resolve) = > {setTimeout (() = > {resolve (10)}, 500)}) / / after obtaining the data Call the existing action this.setCount (count)}}) store.initCount ()
Listen for object changes
Whether you want to introduce MobX in React or Mini Program, you need to call the native setState/setData method to synchronize the state to the view when the object changes.
This capability can be achieved through the autorun method, and we can think of autorun as the useEffect in React Hooks. Whenever the response property of the store is modified, the method passed into the autorun (effect) is called once.
Import {autorun, makeAutoObservable} from 'mobx' const store = makeAutoObservable ({count: 0, setCount (count) {this.count = count}, increment () {this.count++}) Decrement () {this.count--}}) document.getElementById ("increment"). Onclick = function () {store.count++} const $count = document.getElementById ("count") $count.innerText = `$ {store.count} `autorun (() = > {$count.innerText = `${store.count}`})
Whenever the button#increment button is clicked, the values in the span#count are automatically synchronized. ?? View the complete code.
Effect demonstration
In addition to autorun, MobX also provides more refined listening methods: reaction, when.
Const store = makeAutoObservable ({count: 0, setCount (count) {this.count = count}, increment () {this.count++}, decrement () {this.count--}}) / / store calls effect autorun immediately after modification (() = > {$count.innerText = `${store.count}`}) / / the following effect reaction will not be called until the return value of the first method is modified (/ / means that store.count will be called after modification () = > store.count, / / the first parameter is the current value, and the second parameter is the value before modification / / is somewhat similar to watch (value, prevValue) = > {console.log ('diff', value-prevValue)} in Vue). / / the return value of the first method is true. Immediately call the following effect when (() = > store.count > 10, () = > {console.log (store.count)}) / / when method can also return a promise (async function () {await when () = > store.count > 10) console.log ('store.count > 10')}) () Thank you for reading. That's what MobX is. After the study of this article, I believe you have a deeper understanding of what is MobX, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.