React - Apollo Client,如何将查询结果添加到状态

React - Apollo Client, How to add query results to the state

我创建了一个由 Apollo 客户端和 graphQL 驱动的 React 应用程序。
我的架构已定义,因此预期结果是一个对象数组 ([{name:"metric 1", type:"type A"},{name:"metric 2", type:"type B"}])

在我的 jsx 文件中,我定义了以下查询:

query metrics($id: String!) {
  metrics(id: $id) {
    type
    name
  }
}`;

我已经用 Apollo HOC 包装了组件,如下所示:

export default graphql(metricsQuery, {
  options: (ownProps) => {
    return {
      variables: {id: ownProps.id}
    }
  }
})(MetricsComp);

Apollo 客户端工作正常,returns 渲染方法中道具的预期列表。


我想让用户在客户端上操作结果(编辑/从列表中删除一个指标,不需要对服务器上的实际数据进行修改)。然而,由于结果在组件道具上,我必须将它们移动到状态以便能够变异。如何在不导致无限循环的情况下将结果移动到状态?

如果阿波罗在这件事上像中继一样工作,你可以尝试使用componentWillReceiveProps:

class ... extends Component {

  componentWillReceiveProps({ metrics }) {
    if(metrics) {
      this.setState({
        metrics,
      })
    }  
  }
}

像这样。

componentWillReceiveProps 即将弃用 (reference link)

如果您使用的是 React 16,那么您可以这样做:

class DemoClass extends Component {
  state = {
    demoState: null // This is the state value which is dependent on props
  }

  render() {
    ...
  }
}

DemoClass.propTypes = {
  demoProp: PropTypes.any.isRequired,  // This prop will be set as state of the component (demoState)
}

DemoClass.getDerivedStateFromProps = (props, state) => {
  if (state.demoState === null && props.demoProp) {
    return {
      demoState: props.demoProp,
    }
  }
  return null;
}

您可以通过阅读以下内容了解更多信息:link1, link2

你可以使用这个:

import {useState} from 'react';
import {useQuery} from '@apollo/client';

const [metrics,setMetrics]=useState();

useQuery(metricsQuery,{
    variables:{id: ownProps.id},
    onCompleted({metrics}){
        setMetrics(metrics);
    }
});