【问题标题】:React - Apollo Client, How to add query results to the stateReact - Apollo 客户端,如何将查询结果添加到状态
【发布时间】:2018-07-25 02:44:21
【问题描述】:

我创建了一个由 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 客户端工作正常,并在 render 方法中的 props 上返回预期列表。


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

【问题讨论】:

    标签: javascript reactjs graphql react-apollo apollo-client


    【解决方案1】:

    你可以用这个:

    import {useState} from 'react';
    import {useQuery} from '@apollo/client';
    
    const [metrics,setMetrics]=useState();
    
    useQuery(metricsQuery,{
        variables:{id: ownProps.id},
        onCompleted({metrics}){
            setMetrics(metrics);
        }
    });
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        【解决方案3】:

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

        class ... extends Component {
        
          componentWillReceiveProps({ metrics }) {
            if(metrics) {
              this.setState({
                metrics,
              })
            }  
          }
        }
        

        类似的东西。

        【讨论】:

        • 谢谢,我去看看
        • 像魅力一样工作! :)
        • componentWillReceiveProps 即将被弃用
        猜你喜欢
        • 2020-01-23
        • 2020-11-07
        • 2019-02-08
        • 2018-06-28
        • 2021-12-04
        • 2020-04-11
        • 2020-02-15
        • 2017-12-20
        • 2018-03-18
        相关资源
        最近更新 更多