在React中使用GraphQL Mutation时,如果变量的值未传递给Mutation组件,可以按照以下步骤进行解决。
import { gql, useMutation } from '@apollo/client';
const CREATE_USER = gql`
mutation createUser($name: String!, $email: String!) {
createUser(name: $name, email: $email) {
id
name
email
}
}
`;
function CreateUserForm() {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [createUser, { loading, error }] = useMutation(CREATE_USER);
const handleSubmit = (e) => {
e.preventDefault();
// 调用Mutation,并传递变量的值
createUser({ variables: { name, email } })
.then((res) => {
// 处理成功的响应
})
.catch((error) => {
// 处理错误
});
};
// 渲染表单和处理逻辑
}
确保在调用Mutation时,通过variables
属性传递了变量的值。在上面的代码示例中,我们通过createUser({ variables: { name, email } })
将name
和email
变量的值传递给了Mutation。
确保在Mutation定义中正确地使用了变量。在上面的代码示例中,我们在Mutation定义中使用了$name
和$email
来表示变量。
通过以上步骤,你可以确保变量的值被正确地传递给GraphQL Mutation组件。
下一篇:变量的值为什么不会改变