假设我在React-Apollo中有以下GraphQL查询
const CurrentUserForLayout = gql` query CurrentUserForLayout($avatarID: Int!) { currentUser { avatar_url(avatarID: $avatarID) } } `; const ProfileWithData = graphql(CurrentUserForLayout, { options: { variables: { avatarID: 1 } }, })(Profile);
现在,如果我想让我的React组件Profile更改avatarID,
Profile
我该怎么做?
我是React和GraphQl的新手,我不太了解这里的连接:
graphql(CurrentUserForLayout, { options: { variables: { avatarID: 1 } }, })(Profile);
我真的需要周围的另一个父组件ProfileWithData 来将另一个传递avatarID给查询吗?但是,如果ID由Profile组件操纵,该如何让Parent组件知道呢?
ProfileWithData
avatarID
到目前为止,我知道两种可能的解决方法。
第一个 问题中一个已经说明。变量同时是的道具ProfileWithData。因此,您需要找到一种方法来更改道具并重新渲染组件。这通常是通过父组件实现的。因此,通常您不会在中更改变量ProfileWithData。此组件应仅用于显示目的。但是,这并不表示无法完成。您可以将父组件的方法传递给子组件,以操纵父组件的状态。这将重新渲染两个组件,并ProfileWithData使用新的prop /变量进行渲染。
第二种 方法是从ProfileWithData组件内部进行查询。然后,您可以从带有状态的组件内部操作变量。可以在这里找到一种方法
您可以通过使用withApollo高阶组件传递对Apollo Client的引用来实现此 目的,如此处所述:http : //dev.apollodata.com/react/higher-order- components.html#withApollo 然后,您可以client.query像这样调用传入的对象: class MyComponent extends React.Component { runQuery() { this.props.client.query({ query: gql`...`, variables: { ... }, }); } render() { ... } } withApollo(MyComponent);
您可以通过使用withApollo高阶组件传递对Apollo Client的引用来实现此 目的,如此处所述:http : //dev.apollodata.com/react/higher-order- components.html#withApollo
withApollo
然后,您可以client.query像这样调用传入的对象:
client.query
class MyComponent extends React.Component { runQuery() { this.props.client.query({ query: gql`...`, variables: { ... }, }); } render() { ... } } withApollo(MyComponent);