Mobx 4.3.1, Mobx-React 5.1.0.
background
When I was recently working on an RN project, I came across a situation where the data source wasObservableArray
Format, and then pass the data source toFlatList
.The demo address.At this point, the user needs to modify the list with every clickitem
, and need to re-render the page at the same time. We all know that if we need a component to rerender, we only need to use this componentobserver
Just wrap it up. But now we have a problem. The component we are using is a third-party component and we cannot wrap its source codeobserver
. So how do we get the data back to the page? Of course, like me, most people’s first thought would be to change the array reference address, at which point the data would be rendered back onto the page. But doing so, it seems abnormal, always feel too complicated, MingMobX
It’s reactive, and every item in our data sourceitem
Are allobservable
Then why can’t it be amendeditem
To allow the page to be re-rendered?
The solution
mobx-react
providesObserver
Component, we only need to useObserver
Under the parcelrenderItem
The return value of. At this point, when we click on each item, the page rerenders,The demo address.
Why is the Observer component implemented
Observer
The component passes through internallyobserver
The function wraps the incoming component to make it responsive.
Why can the Observer make components responsive
The observer function is intermixed with the lifecycle function and shallowEqual in the shouldComponentUpdate lifecycle function, so there is no need to use PureComponent when using an observer. Next, rewrite the Render method as the return value of the makeComponentReactive function. Internally, this function listens for changes in values through Reaction and updates the component through the forceUpdate method if the referenced value changes.