用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 连接电脑的模拟器问题