componentDidMount只执行一次的解决方法

一、前言

最近写react antd前端项目,需要页面加载时调用下查询列表的接口。

于是在componentDidMount方法里这样写了:

  componentDidMount() {
    const {
      dispatch,
      MyJS: { queryPara },
    } = this.props;

    //这个调用接口查询列表
    dispatch({ type: 'MyJS/fetch', queryPara });
  }

之后,当首次打开这个页面时,确实可以查询到数据列表;

但是关闭这个页面后再次打开,就发现没有数据了,componentDidMount没有执行。

二、解决方法

1.由于关闭页面时,没有销毁这个页面,因此再次打开这个页面,页面不会重新加载,就不会调用componentDidMount方法。

2.因此,可以在引入页面的标签中,加上destroyOnClose,样例如下:

        <Drawer
          width={1200}
          title="选择列表"
          placement="right"
          closable={false}
          onClose={this.onClose1}
          visible={visible1}
          destroyOnClose
        >
          <Mypage onClose={this.onClose1} />
        </Drawer>

说明:
(1)Drawer标签是import { Drawer } from 'antd';
(2)closable={false}是样式,false时右上角没有关闭按钮,true时有。
(3)visible控制这个子页面打开或者关闭
(4)加上destroyOnClose,就可以当页面关闭后,销毁页面,下次再打开页面就能触发componentDidMount方法了。(如果需要缓存页面、不需要销毁,那就去掉这个)
(5)Mypage标签是自己写的一个页面,import Mypage from './mypage/index';
(6)onColse是页面被关闭时会调用的方法

猜你喜欢

转载自blog.csdn.net/BHSZZY/article/details/134074926
今日推荐