简体   繁体   中英

ReactJs how to pass data between components

I'v e been learning react and am slowing developing an understanding for how to pass data between components. On a simplify basis there seems to be 4 cases:

  1. In parent pass data to child => use props
  2. In parent retrieve data from child => use ref and pass a function down
  3. In child pass data to parent => pass a function down
  4. In child retrieve data from parent

It's the 4th case I haven't found any guidance on yet. You're in a child and want to get some data from the parent that wasn't pass down as a prop. Can that ever happen?

In addition to context , you can also get data from a parent with a callback

class Parent extends React.Component {
  render() {
    return <Child update={Math.random} />
  }
}

class Child extends React.Component {
  state = { }

  componentDidMount() {
    this.updateState()
  }

  updateState = () => {
    const { update } = this.props
    this.setState({ something: update() }, () => {
      setTimeout(this.updateState, 1000)
    })
  }

  render() {
    return <div>{this.state.something}</div>
  }
}

the one downside to this is that the child has to explicitly request data from the parent (changing the data in the parent will not update the child like it would with context).

Another way to do this is with a global store like redux.

class Parent extends React.Component {
  render() {
    return (
      <div>
        <Child />
        <button onClick={ () => this.props.setSomething(Math.random()) }>click me</button>
      </div>
    )
  }
}

// where setSomething is an action creator that changes `globalState.something`
connect(function (state) {
  return { something: state.something }
}, { setSomething })(Child)

class Child extends React.Component {
  render() {
    return <div>{ this.props.something }</div>
  }
}

connect(function (state) {
  return { something: state.something }
})(Child)

1st and 4th case are more or less the same except the case when child component pull the data from parent rather than data pushed by parent. I am not able to think the in which context it will be useful. It seems to be very unlikely situation. Even if we want to achieve it then one way would be to attach a hook using functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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