Apollo Query 组件如何使用它的自身值作为回调
How Apollo Query component use it's self value as callback
我正在阅读 apollo documentation 然后我看到了下面的代码。
似乎可以传递来自查询组件本身的加载、错误和数据,并且 props.children 接受函数。我怎样才能实现这样一个简单的组件,它可以获取自己的值并将其传递给它的child?
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
。 (我猜 apollo 查询组件使用了这个方法,因为根据它是 source code。
2) 克隆 children 然后发送对我来说不成功的数据。
允许 children 成为一个函数是 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);
}
有关 in-depth 函数作为 children 模式的更多解释,请查看有关渲染道具的 React documentation。
我正在阅读 apollo documentation 然后我看到了下面的代码。 似乎可以传递来自查询组件本身的加载、错误和数据,并且 props.children 接受函数。我怎样才能实现这样一个简单的组件,它可以获取自己的值并将其传递给它的child?
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
。 (我猜 apollo 查询组件使用了这个方法,因为根据它是 source code。
2) 克隆 children 然后发送对我来说不成功的数据。
允许 children 成为一个函数是 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);
}
有关 in-depth 函数作为 children 模式的更多解释,请查看有关渲染道具的 React documentation。