我有两个组件,在我的componentDidMount生命周期方法中,我从服务器获取所有项目的ajax调用请求。
//Routes in primary parent component that render 2 components
<div className="primary">
<Switch>
<Route path="/admin/manage-regions" exact component={() =>
<ManageRegions />} />
<Route path="/admin/manage-practices" exact component={() =>
<ManagePractices />} />
</Switch>
</div>
//First component
componentDidMount() {
console.log('called twice');
const { getAllRegionsAction } = this.props;
getAllRegionsAction({ path: 'regions', filterName: 'regions' });
}
//Second component
componentDidMount() {
console.log('called twice');
const { getAllPracticesAction } = this.props;
getAllPracticesAction({ path: 'practice', filterName: 'practices' });
}
export default connect(
null,
{
getAllRegionsAction: getAllFilters,
},
)(MyFirstComponent);
export default connect(
null,
{
getAllPracticesAction: getAllFilters,
},
)(MySecondComponent);
问题是我的componentDidMount方法被调用两次。因此,我将两个动作(GET_ALL_FILTERS)推送到我的商店而不是一个,这就是为什么我从服务器而不是一个接收到两个响应。它看起来像:“component-is-rendered-component-is-removed-component-is-rendered”(甚至在视觉上)。我在componentWillUnmount方法中检查了它。实际上,在初始加载期间,组件被渲染,然后被移除,然后另一个渲染被调用,这就是我在componentDidMount中获得两个console.log的原因。经过一些研究类似的问题,我尝试使用路由器,只留下一个组件等等......但没有任何帮助。 componentDidMount仍然被调用两次。
组件是否在同一页面上?如果是,只需在其父组件中发出请求即可。如果不是,你可以玩缓存。