用react-service做状态管理,适用于react、react native
转载自:https://blog.csdn.net/wo_shi_ma_nong/article/details/100713151 。
react-service是一个非常简单的用来在react、react native中进行状态维护的包。
其用法非常简单,只有有限的几个属性和方法,非常好用。
官方文档在这里:https://github.com/caoyongfeng0214/react-service 。
用法如下:
首先,在自己的react或react native项目中安装包:
npm install r-service -save注意: 安装的包名是r-service,而不是react-service。实际上react-service是另一个不同的包。
在react-service的概念里,Service是数据与UI之间的桥梁。Service用来处理数据,并维护状态,UI只负责数据的展示。可为每一类数据创建一个Service。
可将所有的Service放在./service文件夹下。
以下为官方文档上的一个小示例:
./service/User.js
import Service from 'r-service';class User extends Service{ // 每个Service继承自react-service中的Service gets(){if(!this.$data.users){ // 数据存储在 $data 中// HTTP调用服务端提供的接口获取数据var users = [{id: 10, name: 'CYF'},{id: 20, name: '张三丰'},{id: 30, name: '袁崇焕'}];// 将数据使用 $set 方法存储到 $data 中this.$set('users', users);}}remove(id){var idx = this.$data.users.findIndex((T) => {return T.id == id;});if(id >= 0){this.$data.users.splice(idx, 1);// 数据发生改变后,并不会立即应用到UI中,需调用 $apply 方法使之体现到UI中this.$apply();}// // 第二种方式// var users = this.$data.users.filter((T) => {// return T.id != id;// });// // 使用 $set 方法重新设置数据,将立即体现在UI中,而不用调用 $apply 方法// this.$set('users', users); } }每个Service需继承自react-service,其从父类中继承了一些方法和属性。所有数据存储在$data中。
当$data中的数据发生改变后,需调用$apply()方法使更改体现到UI中。但如果使用$set(key, value)方法设置数据,则不用调用$apply()。
在UI中,绑定Service的$data中的数据。
./App.js
import React from 'react'; import {View, Text, Button} from 'react-native';import User from './service/User';class App extends React.Component {constructor(props){super(props);// 初始化Service,将当前组件作为参数传入,// 这样,当前组件的状态就能在Service中维护了this.user = User.init(this);// 调用Service中的方法获取数据this.user.gets();}remove(id){// 调用Service中的remove方法this.user.remove(id);}render(){// UI中的数据从Service的$data获取return <View>{this.user.$data.users?this.user.$data.users.map((T) => {return <View><Text>{T.id} : {T.name}</Text><Button title="Remove" onPress={()=>this.remove(T.id)}/></View> }):null}</View> } }以上是官方文档上的示例。
我再稍候补充一下,在另一个页面中展示同样的用户列表:
./pages/Users.js
import React from 'react'; import {View, Text} from 'react-native';import User from './service/User';class Users extends React.Component {constructor(props){super(props);this.user = User.init(this);}render(){return <View>{this.user.$data.users?this.user.$data.users.map((T) => {return <View><Text>{T.id} : {T.name}</Text></View> }):null}</View> } }其实,第二个页面中使用的Service与第一个页面中的是同一个,因此,在第二个页面虽然没有调用gets()方法,但仍然能够绑定到数据。并且,在第一个页面中对数据的更改,也会同时反应到第二个页面中。
转载于:https://www.cnblogs.com/mafengzi/p/11503631.html
与50位技术专家面对面20年技术见证,附赠技术全景图总结
以上是生活随笔为你收集整理的用react-service做状态管理,适用于react、react native的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 成就卓越代码,从关注细节开始
- 下一篇: HBuilderX 连接电脑的模拟器问题