探讨该问题的原因:
component 组件内import了一个弹窗组件,而这个组件内部的数据需要异步获取。还有一个属性visible用于控制弹窗是否显示。
解决方案一:
- 利用dva model,将 visible 属性设置在 model state 属性上。
- 在effect获取数据后,dispatch事件将 state.visible 设置为 true
该方案存在问题:
model state 属性实例化后永远存在,一旦设置为true,即使页面跳转,再回来该页面时,state.visible仍为true,弹窗就会出现,那么这个不正确。
实现代码:
export default {
namespace: 'organization',
state: {
visible: false,
},
effects: {
// 获取详情
*getDetail({ payload }, { call, put }) {
const response = yield call(getDetail, payload);
yield put({
type: 'getDetailSuccess',
payload: response,
});
},
},
reducers: {
getDetailSuccess(state, action) {
return {
...state,
detail: action.payload,
visible: true,
};
},
},
};
解决方案2:
将visible属性设置在component的 state 上,在effects 获取的action 上增加 callback 方法来触发 component state更新
实现代码:
// models.js 的 effect代码
*getDetail({ payload, callback }, { call, put }) {
const response = yield call(getDetail, payload);
// 判断是否成功。如果成功在打开弹窗
if (response.success) {
if (callback && typeof callback === 'function') {
callback();
}
yield put({
type: 'getDetailSuccess',
payload: response,
});
}
},
// component.js dispatch方法
dispatch({
type: effects.getDetail,
payload: { id: record.id },
callback: () => {
this.setState({
detailVisible: true,
});
},
});