gpt4 book ai didi

reactjs - 如何在 withFormik() 形式中使用 useMutation 钩子(Hook)

转载 作者:行者123 更新时间:2023-12-03 19:12:24 26 4
gpt4 key购买 nike

这个 Formk 表单工作正常,但是当我在表单中使用“useMutation”钩子(Hook)时,它显示错误“在上下文中找不到“客户端”或作为选项传入。将根组件包装在一个中,或传递一个 ApolloClient 实例通过选项”。我也使用了“突变”,它给出了同样的错误。我认为错误在突变部分。

form.js

import React,{useState} from "react"
import {render} from "react-dom"
import {withFormik, Form, Field} from 'formik'
import * as Yup from "yup"
import { useMutation } from '@apollo/react-hooks';
import gql from 'graphql-tag'

const REGISTER_MUTATION=gql`
mutation ($email: String!, $password: String!, $username: String!)
{createUser(
email: $email, username: $username, password: $password){
user{username, email}}
}`;

const App = ({values, errors, touched, isSubmitting })=> {

// Here is the problem, if i remove this portion it works fine
const [username, setUsername]= useState("username");
const [email, setEmail]= useState("email");
const [password, setPassword]= useState("password");

const [createUser] = useMutation(REGISTER_MUTATION)
async function createNewUser() {
await createUser({ variables: { username , email , password },
})
}; console.log(createUser);
//Afterwards it works fine
return(

<Form>
<div>
{touched.email && errors.email && <p>Invalid Email </p>}
<Field type="email" name="email" placeholder="Email" />
</div>
<div>
{touched.password && errors.password && <p>Invalid password </p>}
<Field type="password" name="password" placeholder="Password" />
</div>
<label>
<Field type="checkbox" name="newsletter" checked={values.newsletter}/>
Ok got it
</label>

<Field component="select" name="plan">
<option value="value">Free</option>
<option value= "premium" > Premium</option>
</Field>
<button type="button" disabled={isSubmitting}>Submit</button>
</Form>
);}

const FormikApp = withFormik({
mapPropsToValues ({email, password, newsletter, plan}){
return{
password: password || " ",
email: email || " ",
newsletter: newsletter || true,
plan : plan || 'Premium'
}
},
validationSchema: Yup.object().shape({

email: Yup.string().email("Invalid email account").required("field missing"),
password: Yup.string().email().min(8,"password is weak").required()
}),

handleSubmit(values, setSubmitting){
setTimeout(()=>{
setSubmitting(false)
},2000)
}
})(App)

render(<FormikApp />, document.getElementById("root"))
export default FormikApp


index.js

import React from 'react';
import ReactDOM from 'react-dom';
import * as serviceWorker from './serviceWorker';
import FormikApp from'./component/form1';
import ApolloClient from 'apollo-boost';
import { ApolloProvider } from 'react-apollo';
import { ApolloProvider as ApolloProviderHooks } from '@apollo/react-hooks';

const client = new ApolloClient({ uri: 'http://127.0.0.1:8000/graphql/' });
const App = () => (

<ApolloProvider client={client}>
<ApolloProviderHooks client={client}>
<FormikApp />
</ApolloProviderHooks>
</ApolloProvider>
);

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

serviceWorker.unregister();


包.json

{
"name": "start_react",
"version": "0.1.0",
"private": true,
"dependencies": {
"@apollo/react-hooks": "^3.1.5",
"@emotion/core": "^10.0.28",
"@emotion/styled": "^10.0.27",
"@material-ui/icons": "^4.9.1",
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.5.0",
"@testing-library/user-event": "^7.2.1",
"apollo-boost": "^0.4.7",
"cors": "^2.8.5",
"express": "^4.17.1",
"formik": "^2.1.4",
"graphql": "^15.0.0",
"graphql-tag": "^2.10.3",
"react": "^16.13.1",
"react-apollo": "^3.1.5",
"react-apollo-hooks": "^0.5.0",
"react-dom": "^16.13.1",
"react-scripts": "3.4.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

最佳答案

在您的 form.js不要这样做render(<FormikApp />, document.getElementById("root"))
您正在渲染 <FormikApp />如您所见,您需要包装<FormikApp />使用 ApolloProvider因为useMutation需要 Apollo 客户端。

如果您删除 render(<FormikApp />, document.getElementById("root")) ,我相信你的问题不会持续存在

编辑

工作示例:https://codesandbox.io/s/awesome-ishizaka-kuhxi

你可以为你的 FormikApp 做一个包装。 .像这样的东西:

import React from "react";
import { withFormik, Form, Field } from "formik";
import * as Yup from "yup";
import { useMutation } from "@apollo/react-hooks";
import gql from "graphql-tag";

const REGISTER_MUTATION = gql`
mutation($email: String!, $password: String!, $username: String!) {
createUser(email: $email, username: $username, password: $password) {
user {
username
email
}
}
}
`;

const App = ({ values, errors, touched, isSubmitting }) => {
//Afterwards it works fine
return (
<Form>
<div>
{touched.email && errors.email && <p>Invalid Email </p>}
<Field type="email" name="email" placeholder="Email" />
</div>
<div>
{touched.password && errors.password && <p>Invalid password </p>}
<Field type="password" name="password" placeholder="Password" />
</div>
<label>
<Field type="checkbox" name="newsletter" checked={values.newsletter} />
Ok got it
</label>

<Field component="select" name="plan">
<option value="value">Free</option>
<option value="premium"> Premium</option>
</Field>
<button type="submit" disabled={isSubmitting}>
Submit
</button>
</Form>
);
};

const FormikApp = withFormik({
mapPropsToValues({ email, password, newsletter, plan }) {
return {
password: password || " ",
email: email || " ",
newsletter: newsletter || true,
plan: plan || "Premium"
};
},
validationSchema: Yup.object().shape({
email: Yup.string()
.email("Invalid email account")
.required("field missing"),
password: Yup.string()
.email()
.min(8, "password is weak")
.required()
}),

handleSubmit(values, { props }) {
props.createUser({
variables: values
});
}
})(App);

const FormikWrapper = () => {
const [createUser] = useMutation(REGISTER_MUTATION);
return <FormikApp createUser={createUser} />;
};

export default FormikWrapper;

关于reactjs - 如何在 withFormik() 形式中使用 useMutation 钩子(Hook),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61646743/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com