无法设置 formik 表单的初始值?
Not able to set initial values of formik form?
我创建了一个 formik 表单,它通过 API 调用从后端数据库获取其初始值。出现以下错误:
Type 'undefined' is not assignable to type 'FormikValues'. TS2322
无法解决错误。
代码:
// @ts-ignore
import React, { useState, useEffect } from 'react';
import { Formik, Form, Field } from 'formik';
import {
Typography,
Button,
Grid,
CircularProgress,
Divider,
} from '@material-ui/core';
import * as Yup from 'yup';
import { MyInput } from './comman/MyInput';
import axios from 'axios'
import ThumbUpAltIcon from '@material-ui/icons/ThumbUpAlt';
import Unsubscribed from './Unsubscribed';
const contactSchema = Yup.object().shape({
});
export default function SurveyUnsubscribed(props: any) {
const [isSubmitted, setIsSubmitted] = useState(false);
//const [color, setColor] = useState(true);
const [loading, setLoading] = useState(false);
const [count, setCount] = useState(0);
const [countone, setCountOne] = useState(0);
const [counttwo, setCountTwo] = useState(0);
const [countthree, setCountThree] = useState(0);
const [initialValues, setInitialValues] = useState();
const [state, setState] = useState({
msg: '',
});
let initial:any;
async function getInitialValues() {
try{
const response = await axios.get(`${process.env.REACT_APP_LOCALHOST_DEVELOPMENT_VOTING_API_GET}`)
return response.data;
}catch(error){
console.error(error)
}
}
useEffect(() => {
getInitialValues().then((res:any) => setInitialValues(res));
}, []);
const handleClickCount = () => {
setCount(count + 1);
// setColor(false);
};
const handleClickCountTwo = () => {
setCountTwo(counttwo + 1);
// setColor(false);
}; const handleClickCountThree = () => {
setCountThree(countthree + 1);
// setColor(false);
}; const handleClickCountOne = () => {
setCountOne(countone + 1);
// setColor(false);
};
return (
<React.Fragment>
<Formik
enableReinitialize
initialValues={initialValues}
// count: initial,
// countone: countone,
// counttwo: counttwo,
// countthree: countthree,
// helptext: '',
validationSchema={contactSchema}
onSubmit={(values, { resetForm }) => {
setLoading(true);
console.log(initial)
const data = {
count: values.count,
countone: values.countone,
counttwo: values.counttwo,
countthree: values.countthree,
helptext: values.helptext,
};
console.log(data);
const request = new Request(
`${process.env.REACT_APP_LOCALHOST_DEVELOPMENT_VOTING_API}`,
{
method: 'POST',
headers: new Headers({
'Content-Type': 'application/json',
}),
body: JSON.stringify(data),
},
);
fetch(request)
.then((res) => res.json())
.then((data) => {
if (data.message === 'Thank you for your feedback!') {
setState({
msg: data.message,
});
setIsSubmitted(true);
setTimeout(() => {
setLoading(false);
}, 1500);
} else {
console.log('error');
}
});
setTimeout(() => {
setIsSubmitted(false);
}, 1500);
resetForm();
}}
>
{({ setFieldValue }) => (
<Grid container>
<Grid
item
xs={12}
style={{ paddingLeft: '2em', paddingRight: '2em' }}
>
<Typography
variant="h6"
style={{
marginTop: '1em',
color: '#2F4858',
fontWeight: 'bold',
}}
>
Voting survey </Typography>
<br />
{isSubmitted}
<Form>
<Typography
variant="body1"
style={{
display: 'flex',
alignItems: 'center',
marginBottom: '1em',
}}
>
<Field type="hidden" name="count" component={ThumbUpAltIcon} onClick={handleClickCount} style={{ color: '#C4C4C4', marginRight: '0.4em' }}/>
<Typography
variant="caption"
style={{
position: 'relative',
top: '1.5em',
right: '1.5em',
}}
>
{count}
</Typography>
A </Typography>
<Typography
variant="body1"
style={{
display: 'flex',
alignItems: 'center',
marginBottom: '1em',
}}
>
<Field type="hidden" name="countone" component={ThumbUpAltIcon} onClick={handleClickCountOne} style={{ color: '#C4C4C4', marginRight: '0.4em' }}/>
<Typography
variant="caption"
style={{
position: 'relative',
top: '1.5em',
right: '1.5em',
}}
>
{countone}
</Typography>
B </Typography>
<Typography
variant="body1"
style={{
display: 'flex',
alignItems: 'center',
marginBottom: '1em',
}}
>
<Field type="hidden" name="counttwo" component={ThumbUpAltIcon} onClick={handleClickCountTwo} style={{ color: '#C4C4C4', marginRight: '0.4em' }}/>
<Typography
variant="caption"
style={{
position: 'relative',
top: '1.5em',
right: '1.5em',
}}
>
{counttwo}
</Typography>
C </Typography>
<Typography
variant="body1"
style={{
display: 'flex',
alignItems: 'center',
marginBottom: '1em',
}}
>
<Field type="hidden" name="countthree" component={ThumbUpAltIcon} onClick={handleClickCountThree} style={{ color: '#C4C4C4', marginRight: '0.4em' }}
/>
<Typography
variant="caption"
style={{
position: 'relative',
top: '1.5em',
right: '1.5em',
}}
>
{countthree}
</Typography>
D
</Typography>
<br />
<Typography
variant="h6"
style={{
marginLeft: '2em',
marginTop: '0.5em',
}}
>
What information would help you ?
</Typography>
<Field
id="outlined-multiline-flexible"
type="text"
name="helptext"
component={MyInput}
disabled={isSubmitted}
style={{ marginLeft: '2em' }}
/>
<br />
<br />
<Button
type="submit"
variant="contained"
style={{
background: '#2F4858',
color: 'white',
fontFamily: 'roboto',
fontSize: '1rem',
marginLeft: '2em',
marginBottom: '1em',
}}
>
{loading && (
<CircularProgress
size={25}
color="inherit"
style={{ marginRight: '5px' }}
/>
)}
{loading && <span>submitting</span>}
{!loading && <span>Submit</span>}
</Button>
<br />
{state.msg && (
<Typography
variant="h6"
style={{
color: '#4BB543',
fontFamily: 'roboto-medium',
marginTop: '1em',
}}
>
{' '}
{state.msg}{' '}
</Typography>
)}
</Form>
<Divider
style={{
border: '1px solid #97A1A8',
marginTop: '1em',
marginBottom: '2em',
}}
/>
<Unsubscribed />
</Grid>
</Grid>
)}
</Formik>
</React.Fragment>
);
}
请大家帮我从数据库(Postgresql)
设置formik
初始值
因为您创建状态 initialValues
,默认值为 undefined
。所以只需将默认值更新为一个空对象
const [initialValues, setInitialValues] = useState({});
我创建了一个 formik 表单,它通过 API 调用从后端数据库获取其初始值。出现以下错误:
Type 'undefined' is not assignable to type 'FormikValues'. TS2322
无法解决错误。
代码:
// @ts-ignore
import React, { useState, useEffect } from 'react';
import { Formik, Form, Field } from 'formik';
import {
Typography,
Button,
Grid,
CircularProgress,
Divider,
} from '@material-ui/core';
import * as Yup from 'yup';
import { MyInput } from './comman/MyInput';
import axios from 'axios'
import ThumbUpAltIcon from '@material-ui/icons/ThumbUpAlt';
import Unsubscribed from './Unsubscribed';
const contactSchema = Yup.object().shape({
});
export default function SurveyUnsubscribed(props: any) {
const [isSubmitted, setIsSubmitted] = useState(false);
//const [color, setColor] = useState(true);
const [loading, setLoading] = useState(false);
const [count, setCount] = useState(0);
const [countone, setCountOne] = useState(0);
const [counttwo, setCountTwo] = useState(0);
const [countthree, setCountThree] = useState(0);
const [initialValues, setInitialValues] = useState();
const [state, setState] = useState({
msg: '',
});
let initial:any;
async function getInitialValues() {
try{
const response = await axios.get(`${process.env.REACT_APP_LOCALHOST_DEVELOPMENT_VOTING_API_GET}`)
return response.data;
}catch(error){
console.error(error)
}
}
useEffect(() => {
getInitialValues().then((res:any) => setInitialValues(res));
}, []);
const handleClickCount = () => {
setCount(count + 1);
// setColor(false);
};
const handleClickCountTwo = () => {
setCountTwo(counttwo + 1);
// setColor(false);
}; const handleClickCountThree = () => {
setCountThree(countthree + 1);
// setColor(false);
}; const handleClickCountOne = () => {
setCountOne(countone + 1);
// setColor(false);
};
return (
<React.Fragment>
<Formik
enableReinitialize
initialValues={initialValues}
// count: initial,
// countone: countone,
// counttwo: counttwo,
// countthree: countthree,
// helptext: '',
validationSchema={contactSchema}
onSubmit={(values, { resetForm }) => {
setLoading(true);
console.log(initial)
const data = {
count: values.count,
countone: values.countone,
counttwo: values.counttwo,
countthree: values.countthree,
helptext: values.helptext,
};
console.log(data);
const request = new Request(
`${process.env.REACT_APP_LOCALHOST_DEVELOPMENT_VOTING_API}`,
{
method: 'POST',
headers: new Headers({
'Content-Type': 'application/json',
}),
body: JSON.stringify(data),
},
);
fetch(request)
.then((res) => res.json())
.then((data) => {
if (data.message === 'Thank you for your feedback!') {
setState({
msg: data.message,
});
setIsSubmitted(true);
setTimeout(() => {
setLoading(false);
}, 1500);
} else {
console.log('error');
}
});
setTimeout(() => {
setIsSubmitted(false);
}, 1500);
resetForm();
}}
>
{({ setFieldValue }) => (
<Grid container>
<Grid
item
xs={12}
style={{ paddingLeft: '2em', paddingRight: '2em' }}
>
<Typography
variant="h6"
style={{
marginTop: '1em',
color: '#2F4858',
fontWeight: 'bold',
}}
>
Voting survey </Typography>
<br />
{isSubmitted}
<Form>
<Typography
variant="body1"
style={{
display: 'flex',
alignItems: 'center',
marginBottom: '1em',
}}
>
<Field type="hidden" name="count" component={ThumbUpAltIcon} onClick={handleClickCount} style={{ color: '#C4C4C4', marginRight: '0.4em' }}/>
<Typography
variant="caption"
style={{
position: 'relative',
top: '1.5em',
right: '1.5em',
}}
>
{count}
</Typography>
A </Typography>
<Typography
variant="body1"
style={{
display: 'flex',
alignItems: 'center',
marginBottom: '1em',
}}
>
<Field type="hidden" name="countone" component={ThumbUpAltIcon} onClick={handleClickCountOne} style={{ color: '#C4C4C4', marginRight: '0.4em' }}/>
<Typography
variant="caption"
style={{
position: 'relative',
top: '1.5em',
right: '1.5em',
}}
>
{countone}
</Typography>
B </Typography>
<Typography
variant="body1"
style={{
display: 'flex',
alignItems: 'center',
marginBottom: '1em',
}}
>
<Field type="hidden" name="counttwo" component={ThumbUpAltIcon} onClick={handleClickCountTwo} style={{ color: '#C4C4C4', marginRight: '0.4em' }}/>
<Typography
variant="caption"
style={{
position: 'relative',
top: '1.5em',
right: '1.5em',
}}
>
{counttwo}
</Typography>
C </Typography>
<Typography
variant="body1"
style={{
display: 'flex',
alignItems: 'center',
marginBottom: '1em',
}}
>
<Field type="hidden" name="countthree" component={ThumbUpAltIcon} onClick={handleClickCountThree} style={{ color: '#C4C4C4', marginRight: '0.4em' }}
/>
<Typography
variant="caption"
style={{
position: 'relative',
top: '1.5em',
right: '1.5em',
}}
>
{countthree}
</Typography>
D
</Typography>
<br />
<Typography
variant="h6"
style={{
marginLeft: '2em',
marginTop: '0.5em',
}}
>
What information would help you ?
</Typography>
<Field
id="outlined-multiline-flexible"
type="text"
name="helptext"
component={MyInput}
disabled={isSubmitted}
style={{ marginLeft: '2em' }}
/>
<br />
<br />
<Button
type="submit"
variant="contained"
style={{
background: '#2F4858',
color: 'white',
fontFamily: 'roboto',
fontSize: '1rem',
marginLeft: '2em',
marginBottom: '1em',
}}
>
{loading && (
<CircularProgress
size={25}
color="inherit"
style={{ marginRight: '5px' }}
/>
)}
{loading && <span>submitting</span>}
{!loading && <span>Submit</span>}
</Button>
<br />
{state.msg && (
<Typography
variant="h6"
style={{
color: '#4BB543',
fontFamily: 'roboto-medium',
marginTop: '1em',
}}
>
{' '}
{state.msg}{' '}
</Typography>
)}
</Form>
<Divider
style={{
border: '1px solid #97A1A8',
marginTop: '1em',
marginBottom: '2em',
}}
/>
<Unsubscribed />
</Grid>
</Grid>
)}
</Formik>
</React.Fragment>
);
}
请大家帮我从数据库(Postgresql)
设置formik
初始值
因为您创建状态 initialValues
,默认值为 undefined
。所以只需将默认值更新为一个空对象
const [initialValues, setInitialValues] = useState({});