官术网_书友最值得收藏!

  • React Native Blueprints
  • Emilio Rodriguez Martinez
  • 400字
  • 2021-07-02 15:20:02

The store

MobX uses the concept of "observable" properties. We should declare an object containing our general application's state, which will hold and declare those observable properties. When we modify one of these properties, all the subscribed observers will be updated by MobX automatically. This is the basic principle behind MobX, so let's take a look at a sample code:

/*** src/store.js ***/

import {observable} from 'mobx';

class Store {
@observable feeds;

...

constructor() {
this.feeds = [];
}

addFeed(url, feed) {
this.feeds.push({
url,
entry: feed.entry,
title: feed.title,
updated: feed.updated
});
this._persistFeeds();
}

...

}

const store = new Store()
export default store

We have an attribute, feeds, marked as @observable, meaning that any component can subscribe to it and be notified every time the value is changed. This attribute is initialized as an empty array in the class constructor.

Finally, we also created the addFeed method, which will push a new feed into the feeds attribute and therefore will trigger automatic updates on all the observers. To better understand MobX observers, let's take a look at a sample component observing the feeds list:

import React from 'react';
import { Container, Content, List, ListItem, Text } from 'native-base';
import { observer } from 'mobx-react/native';

@observer
export default class FeedsList extends React.Component {

render() {
const { feeds } = this.props.screenProps.store;
return (
<Container>
<Content>
<List>
{feeds &&
feeds.map((f, i) => (
<ListItem key={i}>
<Text>{f.title}</Text>
</ListItem>
))}
</List>
</Content>
</Container>
);
}
}

The first thing we notice is the need to mark our component with the @observer decorator to ensure it is updated when any of the @observable  properties change in our store. 

By default, React Native's Babel configuration doesn't support the @<decorator> syntax. In order for it to work, we will need to modify our .babelrc file (found in the root of our project) and add transform-decorator-legacy as a plugin. 

Another thing to note is the need for the store to be received in the component as a property. In this case, since we are using react-navigation, we will pass it inside screenProps, which is the standard way in react-navigation for sharing properties between <Navigator> and its child screens. 

MobX has many more features, but we will leave those for more complex apps as one of the goals for this chapter is to show how simple state management can be when we are building small apps.

主站蜘蛛池模板: 六安市| 牡丹江市| 昌吉市| 绍兴县| 青龙| 泸溪县| 历史| 凌云县| 环江| 江山市| 安陆市| 呈贡县| 宿迁市| 大英县| 延寿县| 慈利县| 留坝县| 怀宁县| 万州区| 和静县| 福海县| 乌拉特前旗| 荥经县| 离岛区| 泽普县| 治多县| 高要市| 建瓯市| 牙克石市| 长子县| 和林格尔县| 镇赉县| 玉树县| 江油市| 闻喜县| 宜昌市| 通化县| 扎囊县| 潮州市| 襄汾县| 佛山市|