我们使用mobx都知道,它只是一个状态管理工具,并不能持久化存储数据,这篇文章我将分享如何利用mobx实现持久化存储。
那么我们就从搭建mobx开始:
- 创建应用:
react-native init MobxDemo --version 0.55.3
- 引入mobx:
cd MobxDemo
npm i mobx mobx-react --save
- 安装babel插件 以支持ES7 decorator属性:
npm i babel-plugin-transform-decorators-legacy babel-preset-react-native-stage-0 --save-dev
- 创建.babelrc文件配置babel插件:
{
"presets": ["react-native"],
"plugins": ["transform-decorators-legacy"]
}
mobx配置完毕,开始码代码:
- 新建src/store/index.js和src/store/user.js文件:
user.js
import {AsyncStorage} from 'react-native'
import {observable, computed, action} from 'mobx'
/** 存储登录信息*/
class User {
@observable userbean: any = null;//对象
USER_BEAN_STORAGE = 'USER_BEAN';//保存对象
/**
* 保存对象的action
* @param bean
*/
@action setUserBean = bean => {
this.userbean = bean;
AsyncStorage.setItem(this.USER_BEAN_STORAGE, JSON.stringify(bean))
};
/**
*创建构造函数
*/
constructor() {
this._userBeanStorage();//查询对象
}
/**
* 从本地存储中查询对象
* @returns {Promise<void>}
* @private
*/
async _userBeanStorage() {
let value = await AsyncStorage.getItem(this.USER_BEAN_STORAGE);
this.userbean = value ? JSON.parse(value) : value;
}
}
export default new User()
index.js
import user from './user'
/** 导出mobx状态*/
export default {
user,
}
- 在根目录App.js中引入mobx,将mobx状态设置为全局:
App.js
import React, {Component} from 'react';
import {
StyleSheet,
View
} from 'react-native';
import {Provider} from 'mobx-react/native'
import store from './src/store'
import Main from "./src";
type Props = {};
export default class App extends Component<Props> {
render() {
return (
<View style={styles.container}>
<Provider {...store}>
<Main/>
</Provider>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1
},
});
- 创建App主文件src/index.js
index.js
import React, {Component} from 'react';
import {StyleSheet, Text, View, TouchableOpacity} from 'react-native';
import {inject, observer} from "mobx-react/native";
const userBean = {
id: 123,
name: 'zs',
age: 14,
};
@inject('user')
@observer
export default class Main extends Component<Props> {
constructor(props) {
super(props);
}
render() {
const {user} = this.props;
return (
<View style={styles.container}>
<TouchableOpacity
onPress={() => {
user.setUserBean(userBean)
}}
style={styles.save}
>
<Text>
保存登录信息
</Text>
</TouchableOpacity>
<Text style={styles.text}>
实时显示保存信息: {JSON.stringify(user.userbean)}
</Text>
<TouchableOpacity
onPress={() => {
user.setUserBean(null)
}}
style={styles.clear}
>
<Text>
清除登录信息
</Text>
</TouchableOpacity>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
},
save: {
width: 100,
height: 40,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#10ffd6'
},
clear: {
width: 100,
height: 40,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#ff540b'
},
text: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
});
-
最终我们看一下手机上的效果: