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

React Native学习笔记(五)

2018-03-06  本文已影响156人  于卫国

本文介绍MobX中autorun和@computed的使用及区别。

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

《静夜思》
床前明月光,疑是地上霜。
举头望明月,低头思故乡。
—唐,李白

autorun

autorun 用于当可观察变量发生变化时执行一些命令,例如打印日志、持久化或者更新UI的代码。

接着上文中的例子,添加 autorun 监听count值的变化:
appCountStore.js

import {action, observable} from "mobx";

export default class AppCountStore{
    @observable count = 0;

    @action addCount = () => {
        this.count++;
    };
    
    @action reset = () => {
        this.count=-1;
    };
}

App/index.js

import {autorun} from 'mobx'

const appCount=new AppCountStore();

autorun(() => {
    CustomToast.show("count is "+appCount.count,CustomToast.SHORT);
});

当我们运行程序,autorun 会立即执行一次。autorun 会返回一个参数可用于在执行期间清理 autorun 以及错误处理。

const dispose=autorun(() => {
    if(appCount.count<0){
        throw new Error("count can't less than zero");
    }
    CustomToast.show("count is "+appCount.count,CustomToast.SHORT);
});

dispose.onError(error => {
    CustomToast.show(error.toString(),CustomToast.SHORT);
});

@observer
export default class App extends Component {
    pressButton = () => {
        appCount.addCount();
    };

    pressClean = () => {
        dispose();//清理autorun
    };

    pressException = () => {
        appCount.reset();
    };

    render() {
        console.log("render");
        return (
            <View style={styles.container}>
                <Button onPress={this.pressButton}
                        title="Click Me"
                        color="#841584"/>

                <CountText style={styles.countText} />

                <Button
                    onPress={this.pressClean}
                    title="清理 autorun"
                    color="#FF0000"/>

                <Button
                    onPress={this.pressException}
                    title="捕获异常"
                    color="#0000FF"/>
            </View>
        );
    }
}

@computed

@computed 可以响应式产生一个可以被其它 observer 使用的值。如果该属性没有被使用,则它不会被运行。使用它的UI被销毁后,MobX 会自动将其垃圾回收。@computed 是被高度优化过的,所以尽可能使用它。

import {action, observable,computed} from "mobx";

export default class AppCountStore{
    @observable count = 0;
    ...

    @computed get countThreeTimes(){
        return this.count % 3 === 0;
    }
}

添加显示结果的组件

@observer
export default class App extends Component {
    ...
    render() {
        console.log("render");
        return (
            <View style={styles.container}>
                ...
                <Text>{"count is three times: "+appCount.countThreeTimes}</Text>
            </View>
        );
    }
}

图 运行效果

autorun和@computed之间的区别

经验法则:如果你有一个函数应该自动运行,但不会产生一个新的值,请使用 autorun。 其余情况都应该使用 @computed。

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

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

参考

上一篇 下一篇

猜你喜欢

热点阅读