首页 文章

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

提问于
浏览
2

我创建了一个由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 列表中的指标, no mutation to the actual data on the server is needed ) . 但是由于结果是在组件道具上,我必须将它们移动到状态才能变异 . 如何在不造成无限循环的情况下将结果移动到状态?

2 回答

  • 1

    如果apollo在这个问题上像继电器一样工作,你可以尝试使用 componentWillReceiveProps

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

    这样的事情 .

  • 1

    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

相关问题