Force React container to refresh data

后端 未结 2 768
[愿得一人]
[愿得一人] 2020-12-04 03:31

In my React application, I have two distinct types of components: presentations and containers. It\'s roughly after Dan Abromov\'s \"Presentational and Con

2条回答
  •  盖世英雄少女心
    2020-12-04 03:32

    If you don't want to use Flux or Redux yet, then updating peer-components (in your case, UsersListContainer and AddUserContainer) is a bit, in my opinion, anti-pattern for React.

    The main idea of React is, to me, passing props from parent to children, therefore, Irvin Lim's idea to "got rid of UsersListContainer but moved AddUserContainer into UsersContainer" will make it easier for you to control when to update your component!

    Your current approaching and my idea are the same: in your UsersContainer, create a method to forceUpdate it, then pass it along to AddUserContainer, and after this AddUserContainer added a user, you trigger that updating method on the parent:

    
    

    For your reference, or for anyone else who wants to understand about how to update the parent component whenever child (or grandchild or great-grandchild) updates, please refer to my answer to another similar issue:

    Re-initializing class on redirect

    If you still keep your current component-hierarchy, when UsersContainer is updated, its child-components (UsersListContainer and AddUserContainer) will be updated, too. However, AddUserContainer will once again be updated!

    As a result, I still think in your case, using Flux or Redux is a nice approaching, which eliminates to complexity of passing props through many levels of deep & complicated component-hierarchy

提交回复
热议问题