How to update parent's state in React?

后端 未结 14 1621
粉色の甜心
粉色の甜心 2020-11-22 08:48

My structure looks as follows:

Component 1  

 - |- Component 2


 - - |- Component 4


 - - -  |- Component 5  

Component 3

Component 3 s

14条回答
  •  独厮守ぢ
    2020-11-22 09:41

    If this same scenario is not spread everywhere you can use React's context, specially if you don't want to introduce all the overhead that state management libraries introduce. Plus, it's easier to learn. But be careful, you could overuse it and start writing bad code. Basically you define a Container component (that will hold and keep that piece of state for you) making all the components interested in writing/reading that piece of data its children (not necessarily direct children)

    https://reactjs.org/docs/context.html

    You could also use plain React properly instead.

    
    

    pass doSomethingAbout5 up to Component 1

        
             this.setState({somethingAbout5})}/>
            
        
    

    If this a common problem you should starting thinking moving the whole state of the application to someplace else. You have a few options, the most common are:

    https://redux.js.org/

    https://facebook.github.io/flux/

    Basically, instead of managing the application state in your component you send commands when something happens to get the state updated. Components pull the state from this container as well so all the data is centralized. This doesn't mean can't use local state anymore, but that's a more advanced topic.

提交回复
热议问题