How to update parent's state in React?

后端 未结 14 1380
粉色の甜心
粉色の甜心 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 <h1>{ this.state.text }</h1>
      }
    }
    
    // Click handler
    const onClick = event => {
      dispatcher.dispatch({
        type: 'change'
      })
    }
    
    // Component 5 in your example
    const StatelessChild = props => {
      return <button onClick={ onClick }>Click me</button> 
    }
    

    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.

    0 讨论(0)
  • 2020-11-22 09:25

    This the way I do it.

    type ParentProps = {}
    type ParentState = { someValue: number }
    class Parent extends React.Component<ParentProps, ParentState> {
        constructor(props: ParentProps) {
            super(props)
            this.state = { someValue: 0 }
    
            this.handleChange = this.handleChange.bind(this)
        }
    
        handleChange(value: number) {
            this.setState({...this.state, someValue: value})
        }
    
        render() {
            return <div>
                <Child changeFunction={this.handleChange} defaultValue={this.state.someValue} />
                <p>Value: {this.state.someValue}</p>
            </div>
        }
    }
    
    type ChildProps = { defaultValue: number, changeFunction: (value: number) => void}
    type ChildState = { anotherValue: number }
    class Child extends React.Component<ChildProps, ChildState> {
        constructor(props: ChildProps) {
            super(props)
            this.state = { anotherValue: this.props.defaultValue }
    
            this.handleChange = this.handleChange.bind(this)
        }
    
        handleChange(value: number) {
            this.setState({...this.state, anotherValue: value})
            this.props.changeFunction(value)
        }
    
        render() {
            return <div>
                <input onChange={event => this.handleChange(Number(event.target.value))} type='number' value={this.state.anotherValue}/>
            </div>
        }
    }
    
    0 讨论(0)
  • 2020-11-22 09:27

    For child-parent communication you should pass a function setting the state from parent to child, like this

    class Parent extends React.Component {
      constructor(props) {
        super(props)
    
        this.handler = this.handler.bind(this)
      }
    
      handler() {
        this.setState({
          someVar: 'some value'
        })
      }
    
      render() {
        return <Child handler = {this.handler} />
      }
    }
    
    class Child extends React.Component {
      render() {
        return <Button onClick = {this.props.handler}/ >
      }
    }

    This way the child can update the parent's state with the call of a function passed with props.

    But you will have to rethink your components' structure, because as I understand components 5 and 3 are not related.

    One possible solution is to wrap them in a higher level component which will contain the state of both component 1 and 3. This component will set the lower level state through props.

    0 讨论(0)
  • 2020-11-22 09:29

    I found the following working solution to pass onClick function argument from child to the parent component:

    Version with passing a method()

    //ChildB component
    class ChildB extends React.Component {
    
        render() {
    
            var handleToUpdate  =   this.props.handleToUpdate;
            return (<div><button onClick={() => handleToUpdate('someVar')}>
                Push me
              </button>
            </div>)
        }
    }
    
    //ParentA component
    class ParentA extends React.Component {
    
        constructor(props) {
            super(props);
            var handleToUpdate  = this.handleToUpdate.bind(this);
            var arg1 = '';
        }
    
        handleToUpdate(someArg){
                alert('We pass argument from Child to Parent: ' + someArg);
                this.setState({arg1:someArg});
        }
    
        render() {
            var handleToUpdate  =   this.handleToUpdate;
    
            return (<div>
                        <ChildB handleToUpdate = {handleToUpdate.bind(this)} /></div>)
        }
    }
    
    if(document.querySelector("#demo")){
        ReactDOM.render(
            <ParentA />,
            document.querySelector("#demo")
        );
    }
    

    Look at JSFIDDLE

    Version with passing an Arrow function

    //ChildB component
    class ChildB extends React.Component {
    
        render() {
    
            var handleToUpdate  =   this.props.handleToUpdate;
            return (<div>
              <button onClick={() => handleToUpdate('someVar')}>
                Push me
              </button>
            </div>)
        }
    }
    
    //ParentA component
    class ParentA extends React.Component { 
        constructor(props) {
            super(props);
        }
    
        handleToUpdate = (someArg) => {
                alert('We pass argument from Child to Parent: ' + someArg);
        }
    
        render() {
            return (<div>
                <ChildB handleToUpdate = {this.handleToUpdate} /></div>)
        }
    }
    
    if(document.querySelector("#demo")){
        ReactDOM.render(
            <ParentA />,
            document.querySelector("#demo")
        );
    }
    

    Look at JSFIDDLE

    0 讨论(0)
  • <Footer 
      action={()=>this.setState({showChart: true})}
    />
    
    <footer className="row">
        <button type="button" onClick={this.props.action}>Edit</button>
      {console.log(this.props)}
    </footer>
    
    Try this example to write inline setState, it avoids creating another function.
    
    0 讨论(0)
  • 2020-11-22 09:34

    It seems that we can only pass data from parent to child as react promotes Unidirectional Data Flow, but to make parent update itself when something happens in its "child component", we generally use what is called a "callback function".

    We pass the function defined in the parent to the child as "props" and call that function from the child triggering it in the parent component.


    class Parent extends React.Component {
      handler = (Value_Passed_From_SubChild) => {
        console.log("Parent got triggered when a grandchild button was clicked");
        console.log("Parent->Child->SubChild");
        console.log(Value_Passed_From_SubChild);
      }
      render() {
        return <Child handler = {this.handler} />
      }
    }
    class Child extends React.Component {
      render() {
        return <SubChild handler = {this.props.handler}/ >
      }
    }
    class SubChild extends React.Component { 
      constructor(props){
       super(props);
       this.state = {
          somethingImp : [1,2,3,4]
       }
      }
      render() {
         return <button onClick = {this.props.handler(this.state.somethingImp)}>Clickme<button/>
      }
    }
    React.render(<Parent />,document.getElementById('app'));
    
     HTML
     ----
     <div id="app"></div>
    

    In this example we can make data pass from SubChild -> Child -> Parent by passing function to its direct Child.

    0 讨论(0)
提交回复
热议问题