您可以使用组件上的onCompleted
propsQuery
来设置状态。见下面的例子:
class MyComponent extends React.Component {
constructor (props) {
this.state = {
isFirstRender: true
title: props.post.title
}
}
setTitle = title => {
if (this.state.isFirstRender){
this.setState({title, isFirstRender: false})
}
}
render () {
return <Query
query={POST_QUERY}
variables={{ id: this.props.match.params.id }}
onCompleted={data => this.setTitle(data.post.title)}
>
{({ data, loading, error }) => {
<MyComponent post={data.post}/>
}}
</Query>
}
}
编辑:
由于onCompleted
在最新版本中解决了多次触发的错误react-apollo
,我们现在可以简单地执行以下操作:
...
<Query
query={POST_QUERY}
variables={{ id: this.props.match.params.id }}
onCompleted={data => this.setState({ title: data.post.title})}
>
{({ data, loading, error }) => {
<MyComponent post={data.post}/>
}}
</Query>
)
...