案例2:處理網(wǎng)絡(luò)請(qǐng)求等等操作铐达。
- 在
src/models/home.ts
中 homeModel 接口添加effects 異步action操作
interface HomeModel extends Model {
...
effects:{
asyncAdd: Effect;
}; //處理異步工作的,如異步請(qǐng)求
}
模擬實(shí)現(xiàn)effect異步請(qǐng)求方法
const homdeModel: HomeModel = {
...
effects: {
//第一個(gè)參數(shù) action檬果,第二個(gè)參數(shù)瓮孙,主要是用來(lái)完成異步操作
//等3秒執(zhí)行 add
*asyncAdd({payload}, {call, put}) {
yield call(delay, 3000);
yield put({
type: 'add',
payload,
});
}
},
}
- 在
src/pags/Home.tsx
中調(diào)用一下異步請(qǐng)求
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="跳轉(zhuǎn)到詳情頁(yè)" onPress={this.onPress}></Button>
</View>
);
}
}
異步加載狀態(tài)
傳統(tǒng)的標(biāo)記異步加載的狀態(tài)唐断,給boolean 值,在 請(qǐng)求前 和 請(qǐng)求后 修改 狀態(tài)
Dva 的 loading插件(異步加載狀態(tài))
- 添加插件
yarn add dva-loading-ts
- 導(dǎo)入loading
在src/config/dva.ts
中導(dǎo)入loading
import { create } from "dva-core-ts";
import models from "@/models/index";
import createLoading from "dva-loading-ts";
//1.創(chuàng)建實(shí)例
const app = create();
//2.加載model對(duì)象
models.forEach(model => {
app.model(model);
});
//需要在啟動(dòng)start 前 調(diào)用createLoading方法
app.use(createLoading());
//3.啟動(dòng)dva
app.start();
//4.導(dǎo)出dva的數(shù)據(jù)
export default app._store;
- 在RootState中聲明loading
在src/models/index.tx
中聲明loading對(duì)象
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;
- 在
src/pages/Home.tsx
中獲取loading狀態(tài)
...
//拿到 models 中 home的 num 值
const mapStateToProps = ({ home, loading }: RootState) => ({
num: home.num,
loading: loading.effects['home/asyncAdd'],
});
...
/**
* 首頁(yè)類(lèi)
*/
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: 項(xiàng)目狀態(tài)管理的功能搭建完成了杭抠,可以開(kāi)始進(jìn)入項(xiàng)目擼代碼階段了~
ps: 待完善脸甘,一步一個(gè)??????,up~