【问题标题】:Child component fetches data, which should be passed to parent component子组件获取数据,应该传递给父组件
【发布时间】:2018-09-14 08:26:59
【问题描述】:

在我的 react 组件中,我确实使用 react-apollo 从 graphQL 服务器获取了一些数据。 这很好,但是这个组件是一个 child 组件,我需要将 graphQL 数据获取到父组件。这有可能吗,还是我必须改变我的结构?

儿童

export class Child extends Component {
  const { contentList } = this.props
  render () {
    contentList.map(elm => return <div>elm</div>)
  }
}

export default compose(
  graphql(
    gql`
      query {
        contentList {
          _id
          title
        }
      }
    `, { name: 'contentList' }
  )
)(Child)

家长

export class Parent extends Component {
  constructor () {
    super()
    this.state = {
      data = null // <-- Need to get the data of child here
    }
  }

  render () {
    const { data } = this.state
    // Now I can use the data, which is fetched by the child component
    return <Child />
  }
}

【问题讨论】:

  • 你可以将parent的函数作为prop传递给child,然后从child调用,传递数据。另外:stackoverflow.com/search?q=%5Breact%5D+pass+data+to+parent
  • @ChrisG 但是孩子的电话应该是什么样子?数据通过 compose 附加到子组件...如果我正在使用函数,我知道该怎么做,例如单击子组件的按钮。但在这种情况下,graphql 数据让我感到困惑......
  • 看Parent的render()函数,好像是想在创建之前访问child的数据……?我认为这行不通。
  • @ChrisG 我在考虑渲染父组件,然后渲染子组件,它获取数据,然后将数据传递回父状态,现在使用传递的数据重新渲染父组件...
  • 不要更改render() 中的状态,因为这会导致无限循环。只需将数据的获取移至父级,整个问题就会消失得无影无踪。

标签: javascript reactjs graphql


【解决方案1】:

您可以通过 props 将 parent 的函数传递给 childComponent,并在有数据时从 child 调用该函数。

export class Parent extends Component {
  constructor () {
    super();
    this.handleData = this.handleData.bind(this);
    this.state = {
      data = null // <-- Need to get the data of child here
    }
  }
handleData(data){
//you can use data here
}

  render () {
    const { data } = this.state
    // Now I can use the data, which is fetched by the child component
    return <Child parentHandler="this.handleData" />
  }
}


export class Child extends Component {
  const { contentList, parentHandler } = this.props;
//call parentHandler with the data when you have data
  render () {
    contentList.map(elm => return <div>elm</div>)
  }
}

export default compose(
  graphql(
    gql`
      query {
        contentList {
          _id
          title
        }
      }
    `, { name: 'contentList' }
  )
)(Child)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-07
    • 2017-08-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多