React Native开发经验集React-Native 开发阵营React Native开发

React Native学习笔记(七)

2018-03-19  本文已影响103人  于卫国

本文介绍了MobX中 runInAction 配合 Promise 以及在 async 函数中的使用。

本文首发:http://yuweiguocn.github.io/

《闻王昌龄左迁龙标遥有此寄》
杨花落尽子规啼,闻道龙标过五溪。
我寄愁心与明月,随风直到夜郎西。(随风 一作:随君)
—唐,李白

MobX 中 runInAction 的使用

在前面的文章中提到在严格模式下,所有修改可观察变量的地方必须(放在action中或)添加 @action 装饰器。但 action 包装/装饰器只会对当前运行的函数作出反应,而不会对当前运行函数所调用的函数(不包含在当前函数之内)作出反应!这意味着如果 action 中存在 setTimeout、promise 的 then 或 async 语句,并且在回调函数中某些状态改变了,那么这些回调函数也应该包装在 action 中。这时候我们可以使用 runInAction 包装修改可观察变量。

接下来我们看一个例子,使用 fetch API 获取网络数据,然后使用 runInAction 包装修改可观察变量从而显示到界面上。
appCountStore.js

import {action, observable,computed,runInAction} from "mobx";
export default class AppCountStore{
    ...

    @observable result;

    @action getData = async () => {
        try {
            let movies = await fetch("https://facebook.github.io/react-native/movies.json");
            let text = await movies.text();
            runInAction(() => {
                this.result = text;
            })
        } catch(error) {
            console.log(error);
        }
    };

}

由于 fetch 方法会返回一个Promise,所以上述代码使用 Promise 的写法如下:

@action getData = () => {
   fetch("https://facebook.github.io/react-native/movies.json")
       .then(value => value.text())
       .then(value => {
               runInAction(() => {
                   this.result = value;
               })
           })
       .catch(e => console.log(e));
};

在显示控件中引用store中变量值,当点击按钮时去获取数据。
index.js

pressAsync = () => {
   appCount.getData();
};

render() {
   console.log("render");
   return (
       <View style={styles.container}>
           ...

           <Button
               onPress={this.pressAsync}
               title="Async"
               color="#0000FF"/>

           <Text>{"async result: "+appCount.result}</Text>
       </View>
   );
}

图 运行效果

查看完整源码:https://github.com/yuweiguocn/RNTest

查看React Native学习笔记相关文章

参考

上一篇 下一篇

猜你喜欢

热点阅读