react componentDidMount 数据请求两次

我在componentDidMount请求数据,然后在浏览器里看到我的数据请求了两次,在网上也找到一些答案,但是都没有解决问题。这是找到的一个回答:
react-router3.x hashHistory render两次的bug,及解决方案
然后在控制台打印出来 this.props.router.location.action发现两次都是POP
并没有像上面链接说的那样一个是PUSH一个是POP,请问有人遇到这个问题么?是怎么解决的?
数据请求:

  componentDidMount() {
    window.addEventListener('scroll', this.onScrollHandle);
    if (!this.state.isDraft) {
      this.props.getRate({type: this.state.type, userId: this.state.userId});
      this.handlePageChange(1, 3);
    }
    this.getData();
    console.log(this.props.router.location.action);
    // this.setState({provinceInfo: getProvinceInfo(this.state.provinceId)});
  }

  getData = () => {
    this.props.getApp(this.state.type, this.state.userId);
    this.props.getSimilarApp({ apptype: this.state.type });
  }

react版本如下

"react": "^15.5.4",
"react-dom": "^15.5.4",
"react-redux": "^4.4.2",
"react-router": "^3.0.5",
阅读 11.4k
2 个回答

找到原因了,我在入口文件App.js里请求了一次不同用户权限的接口,而且在渲染的时候返回两个组件,如下:

render() {
    const { isFetching } = this.props.userRole;
    const { Content, Footer } = Layout;
    if (isFetching) {
      return (
        <Spin size="large" spinning={isFetching} tip="加载中..." />
      )
    } else {
      return (
        <Layout>
          ...
        </Layout>
      );
    }
  }

我通过请求userRole接口的isFetching来控制渲染,但是这样做是不正确的,因为一开始isFetching就是false,所以,一开始就会render一次Layout,然后在componentDidMount请求userRole,isFetching变为true,页面卸载Layout,渲染Spin。等userRole请求结束,isFetching=false,继续渲染Layout。从而导致在Detail详情页面请求两次数据。修改后的代码如下:

return (
  <Spin size="large" spinning={isFetching} tip="加载中...">
    <Layout>
     ...
    </Layout>
  </Spin>
);

这个组件在什么地方引用的,导致这个组件mount的两次。
componentDidMount在组件的一个mount中,只能执行一次。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题