RN实战开发

06-项目状态管理--基础方法使用(异步处理effects,lo

2021-08-20  本文已影响0人  Right01

案例2:处理网络请求等等操作。

interface HomeModel extends Model {
    ...
    effects:{
        asyncAdd: Effect;
    }; //处理异步工作的,如异步请求
}

模拟实现effect异步请求方法

const homdeModel: HomeModel = {
    ...
    effects: {
        //第一个参数 action,第二个参数,主要是用来完成异步操作
        //等3秒执行 add
        *asyncAdd({payload}, {call, put}) {
            yield call(delay, 3000);
            yield put({
                type: 'add',
                payload,
            });
        }
    },
}
class Home extends React.Component<IProps> {
    asyncAdd = () => {
        const { dispatch } = this.props;
        dispatch({
            type: 'home/asyncAdd',
            payload: {
                num: 5,
            }
        })
    }

    render() {
        const { num } = this.props;
        return (
            <View>
                <Text>Home {num}</Text>
                <Button title="加" onPress={this.handleAdd}></Button>
                <Button title="异步加" onPress={this.asyncAdd}></Button>
                <Button title="跳转到详情页" onPress={this.onPress}></Button>
            </View>
        );
    }
}

异步加载状态

传统的标记异步加载的状态,给boolean 值,在 请求前 和 请求后 修改 状态

Dva 的 loading插件(异步加载状态)

yarn add dva-loading-ts
import { create } from "dva-core-ts";
import models from "@/models/index";
import createLoading from "dva-loading-ts";
//1.创建实例
const app = create();
//2.加载model对象
models.forEach(model => {
    app.model(model);
});

//需要在启动start 前 调用createLoading方法
app.use(createLoading());

//3.启动dva
app.start();
//4.导出dva的数据
export default app._store;
import { DvaLoadingState } from 'dva-loading-ts';
import home from './home';
const models = [home];
export type RootState = {
    home: typeof home.state;
    loading: DvaLoadingState;
};
export default models;
...

//拿到 models 中 home的 num 值
const mapStateToProps = ({ home, loading }: RootState) => ({
    num: home.num,
    loading: loading.effects['home/asyncAdd'],
});

...

/**
 * 首页类
 */
class Home extends React.Component<IProps> {
    ...
    asyncAdd = () => {
        const { dispatch } = this.props;
        dispatch({
            type: 'home/asyncAdd',
            payload: {
                num: 5,
            }
        })
    }

    render() {
        const { num, loading } = this.props;
        return (
            <View>
                <Text>Home {num}</Text>
                <Text>{ loading ? '正在加载中...' : ''}</Text>
                <Button title="加" onPress={this.handleAdd}></Button>
                <Button title="异步加" onPress={this.asyncAdd}></Button>
                ...
            </View>
        );
    }
}
image.png

ps: 项目状态管理的功能搭建完成了,可以开始进入项目撸代码阶段了~
ps: 待完善,一步一个👣👣👣,up~

上一篇 下一篇

猜你喜欢

热点阅读