How to update parent's state in React?

后端 未结 14 1710
粉色の甜心
粉色の甜心 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:22

    I like the answer regarding passing functions around, its a very handy technique.

    On the flip side you can also achieve this using pub/sub or using a variant, a dispatcher, as Flux does. The theory is super simple, have component 5 dispatch a message which component 3 is listening for. Component 3 then updates its state which triggers the re-render. This requires stateful components, which, depending on your viewpoint, may or may not be an anti-pattern. I'm against them personally and would rather that something else is listening for dispatches and changes state from the very top-down (Redux does this, but adds additional terminology).

    import { Dispatcher } from flux
    import { Component } from React
    
    const dispatcher = new Dispatcher()
    
    // Component 3
    // Some methods, such as constructor, omitted for brevity
    class StatefulParent extends Component {
      state = {
        text: 'foo'
      } 
    
      componentDidMount() {
        dispatcher.register( dispatch => {
          if ( dispatch.type === 'change' ) {
            this.setState({ text: 'bar' })
          }
        }
      }
    
      render() {
        return 

    { this.state.text }

    } } // Click handler const onClick = event => { dispatcher.dispatch({ type: 'change' }) } // Component 5 in your example const StatelessChild = props => { return }

    The dispatcher bundles with Flux is very simple, it simply registers callbacks and invokes them when any dispatch occurs, passing through the contents on the dispatch (in the above terse example there is no payload with the dispatch, simply a message id). You could adapt this to traditional pub/sub (e.g. using the EventEmitter from events, or some other version) very easily if that makes more sense to you.

提交回复
热议问题