我们由src/page/list/basiclist.js文件为例:
由dispatch发起model的里action请求:
handleSubmit = e => {
e.preventDefault();
const { dispatch, form } = this.props;
const { current } = this.state;
const id = current ? current.id : '';
setTimeout(() => this.addBtn.blur(), 0);
form.validateFields((err, fieldsValue) => {
if (err) return;
this.setState({
done: true,
});
//触发action的相关model层的state初始化
dispatch({
type: 'list/submit',
//携带参数传递给后端
payload: { id, ...fieldsValue },
});
});
};
deleteItem = id => {
const { dispatch } = this.props;
dispatch({
type: 'list/submit',
payload: { id },
});
};
进入src/models/list.js文件中调用model的effects方法(相当于redux的middleware),在effects里面可以调用services方法进行异步请求;
effects 用于处理异步操作,不能直接修改 state,由 action 触发,也可触发 action。它只能是 generator 函数,并且有 action 和 effects 两个参数。第二个参数 effects 包含 put、call 和 select 三个字段,put 用于触发 action,call 用于调用异步处理逻辑,select 用于从 state 中获取数据。
//model的state名字,匹配action行为的type属性前缀
namespace: 'list',
state: {
list: [],
},
effects: {
*submit({ payload }, { call, put }) {
let callback;
if (payload.id) {
callback = Object.keys(payload).length === 1 ? removeFakeList : updateFakeList;
} else {
callback = addFakeList;
}
//同时进行多个异步http调用,当最后一个http调用完成后得到返回的结果,相当于promise.all
//effects里面调用servies的方法时yield call
const response = yield call(callback, payload);
console.log(response, 'response')
//effects里面yield put 方法用于触发action
yield put({
type: 'queryList',
payload: response,
});
},
},
src/servier/api
ant-design-pro已经对fetch进行了封装,直接把参数传递过去,并请求对于的api接口即可
export async function removeFakeList(params) {
const { count = 5, ...restParams } = params;
return request(`/api/fake_list?count=${count}`, {
//向后端请求api接口的方法
method: 'POST',
body: {
...restParams,
//需要执行的操作
method: 'delete',
},
});
}
export async function addFakeList(params) {
const { count = 5, ...restParams } = params;
return request(`/api/fake_list?count=${count}`, {
method: 'POST',
body: {
...restParams,
method: 'post',
},
});
}
export async function updateFakeList(params) {
const { count = 5, ...restParams } = params;
return request(`/api/fake_list?count=${count}`, {
method: 'POST',
body: {
...restParams,
method: 'update',
},
});
}
拿到异步请求数据,触发reducer修改state的数据(唯一修改model层state数据的方式就是触发reducer)
reducers: {
queryList(state, action) {
return {
...state,
list: action.payload,
};
},
}
state数据变化,触发所有连接此state的容器组件调用render方法就行重新渲染
//连接model层的state数据,然后通过this.props.state名(namesapce)访问model层的state数据
@connect(({ list }) => ({
list
}))
通过this.props.namespace.data调用所获取的数据
const { list: { list }} = this.props;
如有疑惑,请指正,谢谢!