【发布时间】: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