【问题标题】:How Apollo Query component use it's self value as callbackApollo Query 组件如何使用它的自身值作为回调
【发布时间】:2019-01-15 15:00:28
【问题描述】:

我正在阅读 apollo documentation 然后我看到了下面的代码。 似乎可以传递来自 Query 组件本身的加载、错误和数据,并且 props.children 接受函数。我怎样才能实现这样一个简单的组件,它可以获取自己的值并将其传递给它的孩子?

import gql from "graphql-tag";
import { Query } from "react-apollo";

const GET_DOGS = gql`
  {
    dogs {
      id
      breed
    }
  }
`;

const Dogs = ({ onDogSelected }) => (
  <Query query={GET_DOGS}>
    {({ loading, error, data }) => {
      if (loading) return "Loading...";
      if (error) return `Error! ${error.message}`;

      return (
        <select name="dog" onChange={onDogSelected}>
          {data.dogs.map(dog => (
            <option key={dog.id} value={dog.breed}>
              {dog.breed}
            </option>
          ))}
        </select>
      );
    }}
  </Query>
);

我尝试了什么: 1) 使用发送数据的功能覆盖props.children。 (我猜阿波罗查询组件使用了这种方法,因为它是source code。 2)克隆孩子,然后发送对我来说不成功的数据。

【问题讨论】:

    标签: javascript reactjs apollo react-apollo


    【解决方案1】:

    允许孩子成为一个函数是 React 中的一种常见模式。甚至新的Context API 也使用这种模式。

    如果您查看source code of the react-apollo Query component,您会发现它只是将this.props.children 作为函数调用。

    render() {
      const { children } = this.props;
      const queryResult = this.getQueryResult();
      return children(queryResult);
    }
    

    关于 Function as children 模式的更深入解释,请查看 React documentation 关于渲染道具。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-19
    • 2020-12-04
    • 2019-10-05
    • 2019-01-25
    • 2019-10-12
    • 1970-01-01
    • 2020-01-09
    • 1970-01-01
    相关资源
    最近更新 更多