Create a new page
src/pages
Folder, create a new page, the directory structure is as follows:
> Shipping
> components
> models
index.jsx
Configuring Routing
config/config.js
In accordance, pro exemplary configuration routes
The whole process of state management
这里指的是使用状态管理的整个思路,不是指代码的书写顺序,代码的书写过程应该是下面的倒序
The first step: @connect(() => ({}))
adding before the assembly declared
Here is my habit to state
put the assembly, but not on model
the
If state
placed model
in @connect(() => ({}))
, the necessary received model
instate
The second step: Each event must send a request to the backend, each event will triggerdispatch
Get dispatch
this method
const { dispatch } = this.props
dispatch
usage of
dispatch({
type: '[model文件名]/[effects中的方法]',
payload: [传递参数],
callback: res => {
// 拿到 effects 方法中 callback 传回来的数据,做相应处理,这里我主要是把数据更新到 组件的 state 中
this.setState({
...
})
}
})
The third step: model
file
model
The main content of the file
export default {
namespace: '[对应文件名]',
state: {},
effects: {},
reducers: {
// 如果下面 effects 方法中用到 yield put()
// [对应方法](state, { payload }) { // 第一个参数为,初始 state;第二个参数为,effects 中传递过来的 payload
// ...
// return {
// [经过修改后的 state]
// }
// }
},
};
effects
method
// 实例代码
*fetch({ payload, callback }, { call }) {
const res = yield call(query, 'shipping', payload);
// 如果 dispatch 有传过来一个 callback 的函数的话,调用这个 callback,把 res 作为参数传递,调用组件中的 callback
if (callback) callback(res);
// 这里为什么是如果?因为可以用另一种方法代替 callback 的使用,就是
// yield put({ type: [reducers 中的方法], payload})
},
effects
Medium manneryield call()
import { [接口名] } from '@/services/api';
const res = yield call([接口名], '[接口参数]', payload); // 第三个参数为详细参数,对应 services 文件中的 params
Fourth step: services/api.js
file
import request from '@/utils/request'; // 调用接口请求
import { stringify } from 'qs'; // 字符串转换
export async function [接口名](resource, params) { // 第一个参数,对用上面的 [接口参数]
return request(`/api/${resource}?${stringify(params)}`);
}