如何在Apollo GraphQL查询中使用组件状态作为变量
解决组件state传入GraphQL查询的问题
嘿,我懂你现在的困扰——你想把组件内部state里的clientId传给GraphQL查询,但当前的graphql高阶组件根本读不到组件的state对吧?
问题根源
你写的options:(state) =>...里的state并不是组件内部的state哦!graphql高阶组件的options函数接收的参数是ownProps——也就是父组件传递给当前组件的外部props,所以直接这么写肯定拿不到组件内部的state值。
解决方案
这里给你两种靠谱的解决办法,你可以根据自己的场景选:
方案一:用withApollo手动执行查询
这种方式能让你直接在组件内部访问Apollo Client,从而直接使用组件的state作为查询变量,灵活性更高。
首先导入withApollo:
import { withApollo } from 'react-apollo';
然后修改你的组件代码:
// 注意组件名首字母要大写,React要求组件名必须大写开头 class UsersScreen extends Component { constructor(props) { super(props); this.animatedValue = new Animated.Value(0); this.state = { active: true, clientId: "5acc83c4658e6c2c70b3fe1d", users: [] // 用来存查询到的用户数据 }; } // 组件挂载时执行查询 componentDidMount() { this.fetchUsers(); } // 如果clientId变化,重新查询 componentDidUpdate(prevProps, prevState) { if (prevState.clientId !== this.state.clientId) { this.fetchUsers(); } } // 封装查询逻辑 fetchUsers = async () => { try { const { client } = this.props; const result = await client.query({ query: GET_CLIENT_USERS, variables: { clientId: this.state.clientId } }); this.setState({ users: result.data.clientUsers }); } catch (error) { console.error('查询用户数据出错:', error); } } render() { // 这里可以用this.state.users渲染你的列表 return ( <div> {/* 你的JSX代码 */} </div> ); } } // 用withApollo包裹组件,让组件拿到client属性 export default withApollo(UsersScreen);
方案二:把state值转为props(适合state可从外部传入的场景)
如果你的clientId可以由父组件传递过来,那可以把它作为props传入,然后在graphql高阶组件的options里使用:
class UsersScreen extends Component { constructor(props) { super(props); this.animatedValue = new Animated.Value(0); this.state = { active: true }; } render() { // 渲染组件 return ( <div> {/* 你的JSX代码 */} </div> ); } } export default graphql(GET_CLIENT_USERS, { options: (ownProps) => ({ // 直接从ownProps里拿clientId作为变量 variables: { clientId: ownProps.clientId } }) })(UsersScreen);
然后在父组件里调用时传入clientId:
<UsersScreen clientId="5acc83c4658e6c2c70b3fe1d" />
小提醒
React组件的名字必须是首字母大写的,你原来的usersScreen要改成UsersScreen哦,不然React会把它当成普通HTML标签处理。
内容的提问来源于stack exchange,提问作者404notBrighton
相关产品推荐
相关产品推荐

