React+Apollo Client:如何展示Mutation返回数据?求表单提交指导
Apollo Client Mutation数据展示与表单提交指南
一、解决Mutation返回数据展示问题
1. 函数组件方案(推荐)
用useMutation Hook可直接获取Mutation的执行状态和返回数据,结合条件渲染就能在页面展示内容:
import { useMutation, gql, useEffect } from '@apollo/client'; // 定义你的Mutation const GET_DATA = gql` mutation GetSomeData($input: DataInput!) { getSomeData(input: $input) { id name content } } `; function DataComponent() { // 解构获取mutation函数、数据、加载状态、错误 const [getData, { data, loading, error }] = useMutation(GET_DATA, { variables: { input: { /* 传入你的参数 */ } } }); // 组件挂载时触发Mutation useEffect(() => { getData(); }, [getData]); // 根据状态渲染不同内容 if (loading) return <p>加载中...</p>; if (error) return <p>出错了:{error.message}</p>; // 有数据时渲染内容 return ( <div> <h2>{data.getSomeData.name}</h2> <p>{data.getSomeData.content}</p> </div> ); }
2. 类组件方案
如果坚持用类组件,可使用Mutation组件的render props模式实现:
import { Mutation, gql } from '@apollo/client'; import React from 'react'; const GET_DATA = gql` mutation GetSomeData($input: DataInput!) { getSomeData(input: $input) { id name content } } `; class DataClassComponent extends React.Component { componentDidMount() { // 触发Mutation this.getData(); } render() { return ( <Mutation mutation={GET_DATA} variables={{ input: { /* 传入你的参数 */ } }} > {(getData, { data, loading, error }) => { this.getData = getData; if (loading) return <p>加载中...</p>; if (error) return <p>出错了:{error.message}</p>; return data ? ( <div> <h2>{data.getSomeData.name}</h2> <p>{data.getSomeData.content}</p> </div> ) : null; }} </Mutation> ); } }
二、基于Mutation的表单提交建议
控制表单状态:用React的
useState(函数组件)或类组件state管理输入值:const [formData, setFormData] = useState({ username: '', email: '' }); const handleChange = (e) => { setFormData({ ...formData, [e.target.name]: e.target.value }); };处理提交事件:在表单
onSubmit中调用Mutation函数,传入表单数据作为变量:const handleSubmit = (e) => { e.preventDefault(); submitForm({ variables: { input: formData } }); };状态反馈与防重复提交:利用
loading状态禁用提交按钮,用error状态展示错误信息:<form onSubmit={handleSubmit}> <input name="username" onChange={handleChange} value={formData.username} /> <input name="email" onChange={handleChange} value={formData.email} /> <button type="submit" disabled={loading}> {loading ? '提交中...' : '提交'} </button> {error && <p style={{color: 'red'}}>{error.message}</p>} </form>提交成功后处理:在
useMutation的onCompleted回调里做重置表单、页面跳转等操作:const [submitForm, { loading, error }] = useMutation(SUBMIT_FORM, { onCompleted: () => { setFormData({ username: '', email: '' }); // 示例:跳转成功页 // navigate('/submit-success'); } });
内容的提问来源于stack exchange,提问作者Andres David Ortega Lobo
相关产品推荐
相关产品推荐

