【问题标题】:Set initial state using apollo client使用 apollo 客户端设置初始状态
【发布时间】:2019-06-18 16:42:27
【问题描述】:

我正在尝试使用使用带有 graphql 的 apollo 客户端创建的道具来设置反应状态变量的初始状态。

 this.state = {data:myFunc(this.props.data};

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

【问题讨论】:

  • 你的组件是什么样子的?

标签: reactjs react-apollo graphql-js


【解决方案1】:

我假设 this.props.data 是异步加载的,并且在您尝试将其分配给 this.state 时尚未加载(我假设在构造函数中)。

getDerivedStateFromProps

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 {};
}

https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops

【讨论】:

  • 是的,apollo 客户端确实异步加载数据,是的,状态是在构造函数中设置的。有一个“加载”属性提供给结果,但即使在检查了这个 if (!props.data.loading) ... 结果仍然是空的。
  • 我的错误,我没有删除初始状态调用。这现在工作正常。谢谢。
猜你喜欢
  • 2020-02-22
  • 2017-06-21
  • 1970-01-01
  • 1970-01-01
  • 2021-04-20
  • 2018-06-10
  • 1970-01-01
  • 2020-01-23
  • 2021-12-14
相关资源
最近更新 更多