简体   繁体   English

重新渲染反应时组件闪烁

[英]Components flicker when re-rendering in react

I have a list of favourites in my page and when I click on remove, I will send an API call in my redux action that removes that favourite from the favourites listing. 我的页面上有一个收藏夹列表,当我单击删除时,我将在我的redux操作中发送一个API调用,该调用将从收藏夹列表中删除该收藏夹。 Something like this: 像这样:

constructor(props) {
    super(props);
    this.state = {
        favourite: null
    };

    this.getFavourite();

}

getFavourite() {
   // get api call
}

removeFav(id) {
    const { removeFav } = this.props;

    removeFav(id);
    this.setState({ favourite: null });
}

However, since the API doesn't return the entire list again, I need to call another method to fetch the entire list (now without the one I just removed). 但是,由于API不会再次返回整个列表,因此我需要调用另一种方法来获取整个列表(现在没有刚删除的列表)。

componentDidUpdate(prevState) {
    if (prevState.favourite !== this.state.favourite) {
        this.getFavourites();
    }
}

However, the page seems to flicker a bit every time I click on "Remove" due to this re-rendering. 但是,由于此重新渲染,每次单击“删除”时,页面似乎都会闪烁。

Do I even need to do a componentDidUpdate() or setting the state to null for the favourite is enough? 我甚至需要做一个componentDidUpdate()或将收藏夹的状态设置为null就足够了吗? If I do this, then I don't encounter the flicker but the UI is just updated through the state and not the actual data from the store (unless, I refresh the page since I call getFavourites() when the page loads. 如果执行此操作,则不会遇到闪烁,但UI只是通过状态而不是通过商店中的实际数据进行更新(除非我刷新了页面,因为在页面加载时调用了getFavourites()

If you're using redux, this is the recommended way to do it: 如果您使用的是redux,则建议这样做:

  1. On componentDidMount : dispatch an action which contains fetching api, for you it's getFavorite , then store api data in redux store. componentDidMount :调度一个包含获取api的操作,对您来说它是getFavorite ,然后将api数据存储在redux存储中。
  2. Use mapStateToProps to get the whole list from redux store. 使用mapStateToProps从redux存储获取整个列表。
  3. Apply the list getting from step 2 to UI. 将从步骤2获得的列表应用于UI。
  4. To remove, dispatch an action to call remove api, update the list on redux store. 要删除,请分派一个操作以调用remove api,更新redux存储上的列表。 The rest should be handled by react and redux. 其余的应该由react和redux处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM