05-项目状态管理--基础方法使用(同步处理reducers)
2021-08-20 本文已影响0人
Right01
RN开发中,需要进行数据状态管理。
- 使用redux,就不必多说了,很复杂也很繁琐。
- Dva集成了redux,redux-saga等,使用起来十分便捷。(√)
采用Dva,怎么简单怎么来。感兴趣的可以详细了解Dva的官方文档
项目集成Dva-Core
yarn add dva-core-ts react-redux
# react-redux的js的声明文件
yarn add @types/react-redux
- 案例1:数字相加
src/models/home.ts
文件,
import { Effect, Model } from "dva-core-ts";
import { Reducer } from 'redux';
export interface HomeState {
num: number;
}
interface HomeModel extends Model {
namespace: 'home'; //不可改变,唯一的
state: HomeState; //home的状态,所有数据都会保存到state中
reducers:{
add:Reducer<HomeState>;
}; //处理同步工作的action
// effects:{
// asyncAdd: Effect;
// }; //处理异步工作的,如异步请求
}
const initialState = {
num: 0,
}
const homeModel: HomeModel = {
namespace: 'home',
state: initialState,
reducers: {
add(state, { payload, type }) {
return {
...state,
num: state?.num + payload.num,
}
}
}
}
export default homeModel;
- 将 homeModel 添加到 models中
src/models/index.ts
文件
import home from './home';
const models = [ home];
export type RootState = {
home: typeof home.state;
}
export default models;
- 将model对象添加到Dva中进行管理
src/config/dva.ts
文件
import { create } from "dva-core-ts";
import models from "@/models/index";
//1.创建实例
const app = create();
//2.加载model对象
models.forEach(model => {
app.model(model);
});
//3.启动dva
app.start();
//4.导出dva的数据
export default app._store;
如何使用此dva进行状态管理呢
- 修改
src/index.tsx
,引入组件Provider 包裹 组件,Provider组件可以让它所包裹的所有组件都可以获取到dva的store
import NavigatorStack from "@/navigator/NavigatorStack";
import React from "react";
import { Provider } from "react-redux";
import store from '@/config/dva';
export default class extends React.Component {
render(){
return(
//作用:让组件里面的所有组件都可以获取到dva的store
<Provider store={store}>
<NavigatorStack />
</Provider>
);
}
}
如何能够获取到models/home.ts
里面的num呢?
需要借助一个react-redux库的 connect
函数
import { RootStackNavigation } from "@/navigator/NavigatorStack";
import React from "react";
import { Button, Text, View } from "react-native";
import { connect, ConnectedProps } from 'react-redux';
import { RootState } from "@/models/index";
//拿到 models 中 home的 num 值
const mapStateToProps = ({ home }: RootState) => ({
num: home.num,
});
//获取到函数
const connector = connect(mapStateToProps);
//动态识别 获取到的对象 的 类型
type MadelState = ConnectedProps<typeof connector>;
interface IProps extends MadelState {
navigation: RootStackNavigation;
}
/**
* 首页类
*/
class Home extends React.Component<IProps> {
onPress = () => {
const { navigation } = this.props;
navigation.navigate("Detail", { id: 100 });
}
handleAdd = () => {
const { dispatch } = this.props;
dispatch({
type: 'home/add',
payload: {
num: 10,
}
})
}
render() {
const { num } = this.props;
return (
<View>
<Text>Home {num}</Text>
<Button title="加" onPress={this.handleAdd}></Button>
<Button title="跳转到详情页" onPress={this.onPress}></Button>
</View>
);
}
}
// 导出首页类(用connector 加工一下Home,为props注入models属性)
export default connector(Home);