Dva: effects异步执行后,再更新state怎么做?

Created on 10 Apr 2018  ·  5Comments  ·  Source: dvajs/dva

预期的功能是在effects异步获取数据后,弹窗显示获得的数据。设置组件state标志属性用于组件是否显示。如果把标志位属性放在model的state中在页面跳转的时候,该标志位仍会保留状态返回页面时弹窗就又出现了,这是我不想要的。

question

Most helpful comment

不要用callback,每一个effects在dispatch后都会返回一个promise,在promise中处理弹窗就可以了

All 5 comments

个人觉得弹窗 state 放在 react component 的 state 会比较合适。

如果加在react component 的 state中,那么要在effects回调后如何触发state更新呢?我的问题就是这个。走componentWillReceiveProps 这个的生命周期去改变吗?还是其他的方式?

我想到了个解决方案,不知道这样是否合适。
在dipatch effects action 的时候除了正常的payload ,我将更新state的方法作为参数同样传给了model 的effect,并在之后调用。代码如下:

//  route components.js
showDetail = (record) => {
    const { dispatch } = this.props;
    dispatch({
      type: effects.getDetail,
      payload: { id: record.id },
      callback: () => {
        this.setState({
          detailVisible: true,
        });
      },
    });
  };
// models
effects: {
*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,
        });
      }
    },
}

不要用callback,每一个effects在dispatch后都会返回一个promise,在promise中处理弹窗就可以了

不要用callback,每一个effects在dispatch后都会返回一个promise,在promise中处理弹窗就可以了

那怎么实现呢

Was this page helpful?
0 / 5 - 0 ratings