Reactjs 使用apollo客户端设置初始状态

Reactjs 使用apollo客户端设置初始状态,reactjs,react-apollo,graphql-js,Reactjs,React Apollo,Graphql Js,我试图使用apollo客户端与graphql创建的prop来设置react状态变量的初始状态 this.state = {data:myFunc(this.props.data}; 问题是,设置状态时this.props.data为空。我查看了生命周期方法中的设置,但它仍然返回空。只有在render中调用函数时,我才能获得输出。我假设this.props.data是异步加载的,当您尝试将其分配给构造函数中的this.state时,它尚未加载 在getDerivedStateFromProps

我试图使用apollo客户端与graphql创建的prop来设置react状态变量的初始状态

 this.state = {data:myFunc(this.props.data};
问题是,设置状态时this.props.data为空。我查看了生命周期方法中的设置,但它仍然返回空。只有在render中调用函数时,我才能获得输出。

我假设this.props.data是异步加载的,当您尝试将其分配给构造函数中的this.state时,它尚未加载

在getDerivedStateFromProps中可以进行此操作:


组件的外观如何?是的,apollo客户端确实异步加载数据,是的,状态在构造函数中设置。有一个加载属性提供给结果,但即使在检查了这个if!道具。数据。加载。。。结果仍然是空的。我的错误是,我没有删除初始状态调用。这个现在很好用。谢谢
static getDerivedStateFromProps(props, prevState) {
  if (props.data && !prevState.data) {
    // Only return this when props.data has just loaded. 
    // Figure out the best way to determine that for your code.
    return { data:  myFunc(props.data) };
  }
  return {};
}