我在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",
找到原因了,我在入口文件App.js里请求了一次不同用户权限的接口,而且在渲染的时候返回两个组件,如下:
我通过请求userRole接口的isFetching来控制渲染,但是这样做是不正确的,因为一开始isFetching就是false,所以,一开始就会render一次Layout,然后在componentDidMount请求userRole,isFetching变为true,页面卸载Layout,渲染Spin。等userRole请求结束,isFetching=false,继续渲染Layout。从而导致在Detail详情页面请求两次数据。修改后的代码如下: