在 react-apollo 的 Query 组件中设置状态 [英] Setting state in the Query component of react-apollo

查看:60
本文介绍了在 react-apollo 的 Query 组件中设置状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在尝试为从服务器获取数据的编辑组件设置初始状态,现在应该可以在组件状态下进行编辑.但是当我尝试这样做时:

So, I'm trying to set an initial state for an edit component that gets data from the server and now should be editable in the component state. But when I try to do this:

<Query query={POST_QUERY} variables={{ id: this.props.match.params.id }}>
    {({ data, loading, error }) => {
      this.setState({ title: data.title })

我陷入了无限循环,因为这是在渲染中.我不应该在查询组件中使用组件状态吗?如果没有,有什么替代方案?

I get stuck in an infinite loop since this is in render. Should I not use the component state with the query component? And if not, what is the alternative?

推荐答案

任何需要此数据作为状态的组件都应在 Query 组件内呈现,然后将数据作为支柱.例如:

Whatever component needs this data as state should be rendered inside the Query component, and then have the data passed down to it as a prop. For example:

class MyComponent extends React.Component {
  constructor (props) {
    this.state = {
      title: props.post.title
    }
  }
}

<Query query={POST_QUERY} variables={{ id: this.props.match.params.id }}>
  {({ data, loading, error }) => {
    <MyComponent post={data.post}/>
  }}
</Query>

这篇关于在 react-apollo 的 Query 组件中设置状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆