如何解决如何使用 React.js 进行更改?
我正在尝试使用 graphql 和 react.js 进行一些更改,但我遇到了问题。确实我收到了以下消息:
ESLint: React Hook "useMutation" is called in function "onSubmit" that is neither a React function component nor a custom React Hook function. React component names must start with an uppercase letter.(react-hooks/rules-of-hooks)
但是当我单击以验证表单时需要进行更改,为此我需要函数“onSUbmit”
这是我的代码:
import React from "react";
import { Modal,Button } from "react-bootstrap";
import {useForm} from "react-hook-form";
import {gql,useMutation,useQuery} from '@apollo/client';
import {BrowserRouter,Link,Redirect} from "react-router-dom";
const Register = (props) => {
const { register,handleSubmit,errors } = useForm();
const onSubmit = data => {
let username = data.Username;
const GET_ACTIVITY = gql`
mutation Register($username: String!){
register(username: $username){
username
}
}
`
const [addchannel,{ datas} ] = useMutation(GET_ACTIVITY);
}
console.log(props);
return (
<Modal show={props.show} onHide={props.onClose} centered>
<div className="login-form">
<h3 className="h3 mb-3 font-weight-normal" style={{textAlign: "center"}}> Register</h3>
<form className="form-signin" onSubmit={handleSubmit(onSubmit)} >
<div className="form-group">
<input
type="text"
id="inputUsername"
className="form-control"
placeholder="Username"
required=""
autoFocus=""
name="Username"
ref={register({ required: true})}
/>
<button className="btn btn-outline-success btn-block" type="submit" >
<i className="fas fa-sign-in-alt" /> Register
</button>
<hr />
</div>
</form>
</div>
</Modal>
);
}
export default Register;
你能帮我吗?
非常感谢!
解决方法
这一行 const [addchannel,{ datas} ] = useMutation(GET_ACTIVITY);
实际上并没有调用突变。它只是为您提供了执行此操作的方法。然后,您必须在代码中的其他地方调用 addChannel。这就是为什么对 useMutation 的调用必须在 onSubmit 函数之外。然后在 onSubmit 函数中调用 addChannel()
。然后组件将重新渲染,您可以使用 datas
。
编辑:在我看来,您虽然可以将用户名变量直接传递给模板文字。你永远不必这样做!即便如此,你也必须像这样传递它:
gql`
mutation Register($username: String!){
register(username: ${$username}){
username
}
}
`
但同样,您不应该像这样构建动态查询。
你必须像这样调用你的突变:
addChannel({ // this is the function returned by useMutation
variables: {
username // that's where you pass username !
}
})
因此,您的函数中不需要 GET_ACTIVITY,更不用说调用 useMutation。
,不要在循环、条件或嵌套函数中调用 Hook。
你可以试试这个。
const Register = (props) => {
const { register,handleSubmit,errors } = useForm();
const [addChannel,{ datas} ] = useMutation(GET_ACTIVITY);
const GET_ACTIVITY= gql`
mutation Register($username: String!){
register(username: $username){
username
}
}
`
const onSubmit = data => {
addChannel({ variables: { username: data.Username } });;
}
...
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。