我在默认值方面遇到问题。我从 GET API 获取数据,并希望显示从后端获取的字段中的默认值。 所有值都存在于 initialFieldValuesCopy 中,但我无法在文本字段中显示它们。如果用户想要更改数据,它应该是可更改的意味着用户将能够更改来自后端的数据 我正在使用 PUT API 就像用户更改其工作字段中的数据并且数据存储在后端
代码如下
interface UserData {
id: string;
email: string;
fullName: string;
phone: string;
website: string;
company: string;
country: string;
language: string;
timeZone: string;
currency: string;
description: string;
photoURL: string;
// Add other fields with their types here
}
const AvatarViewWrapper = styled('div')(({ theme }) => {
return {
position: 'relative',
cursor: 'pointer',
'& .edit-icon': {
position: 'absolute',
bottom: 0,
right: 0,
zIndex: 1,
border: `solid 2px ${theme.palette.background.paper}`,
backgroundColor: alpha(theme.palette.primary.main, 0.7),
color: theme.palette.primary.contrastText,
borderRadius: '50%',
width: 26,
height: 26,
display: 'none',
alignItems: 'center',
justifyContent: 'center',
transition: 'all 0.4s ease',
cursor: 'pointer',
'& .MuiSvgIcon-root': {
fontSize: 16,
},
},
'&.dropzone': {
outline: 0,
'&:hover .edit-icon, &:focus .edit-icon': {
display: 'flex',
},
},
};
});
const PersonalInfo = () => {
const { user } = useAuthUser();
const { getRootProps, getInputProps } = useDropzone({
accept: {
'image/png': ['.png', '.jpg', '.jpeg'],
},
onDrop: (acceptedFiles) => {
setImageFile(acceptedFiles[0]);
},
});
const [imageFile, setImageFile] = useState<File | null>(null);
const [initialFieldValues, setInitialFieldValues] = useState<UserData>({
id: '',
email: '',
fullName: '',
phone: '',
website: '',
company: '',
country: '',
language: '',
timeZone: '',
currency: '',
description: '',
photoURL: '/assets/images/placeholder.jpg',
});
useEffect(() => {
// Fetch user details from the GET service
const fetchUserData = async () => {
try {
const token = localStorage.getItem('token');
const response = await axios.get(
'https://admin.accountsdash.com/api/User/account',
{
headers: {
accept: '*/*',
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
},
}
);
const userResponse = response.data;
console.log(userResponse);
// Verify that userResponse is not empty and contains the expected data
if (userResponse) {
// Set the initial field values with the data from the API
setInitialFieldValues({
id: userResponse.id,
email: userResponse.email,
fullName: userResponse.fullName,
phone: userResponse.phoneNumber,
website: userResponse.webSite,
company: userResponse.company,
country: userResponse.country,
language: userResponse.language,
timeZone: userResponse.timeZone,
currency: userResponse.currency,
description: userResponse.description,
photoURL: userResponse.photoURL || '/assets/images/placeholder.jpg',
});
} else {
console.error('Received empty or unexpected data from the API.');
}
} catch (error) {
console.error('Error fetching user data:', error);
}
};
fetchUserData();
}, []);
const initialFieldValuesCopy = { ...initialFieldValues };
console.log('Initial Field Values:', initialFieldValues);
return (
<Box
sx={{
position: 'relative',
maxWidth: 550,
}}
>
<Formik
initialValues={initialFieldValues}
validateOnChange={false}
validateOnBlur={true}
onSubmit={(values, { setSubmitting }) => {
handleFormSubmit(values, imageFile, setSubmitting);
}}
>
{({ values, setFieldValue, isSubmitting }) => (
<Form>
<AvatarBox>
<AvatarViewWrapper {...getRootProps({ className: 'dropzone' })}>
<input {...getInputProps()} />
<label htmlFor="icon-button-file">
<AvatarStyle
src={initialFieldValues.photoURL || values.photoURL}
/>
<Box className="edit-icon">
<EditIcon />
</Box>
</label>
</AvatarViewWrapper>
<FullNameBox>
<Typography
sx={{
fontWeight: Fonts.MEDIUM,
}}
>
{initialFieldValues.fullName}
</Typography>
<Typography
sx={{
color: (theme) => theme.palette.text.secondary,
}}
>
{initialFieldValues.email}
</Typography>
</FullNameBox>
</AvatarBox>
<Grid container spacing={2} sx={{ mb: 4 }} alignItems={'center'}>
<Grid item xs={12} md={6}>
<TextField
fullWidth
name="fullName"
label="Full Name"
defaultValue={initialFieldValues.fullName}
onChange={(e) => setFieldValue('fullName', e.target.value)}
/>
</Grid>
<Grid item xs={12} md={6}>
<TextField
fullWidth
name="email"
label="Email"
defaultValue={initialFieldValuesCopy.email}
disabled
/>
</Grid>
<Grid item xs={12} md={6}>
<TextField
fullWidth
name="phone"
label="Phone"
defaultValue={initialFieldValues.phone}
onChange={(e) => setFieldValue('phone', e.target.value)}
/>
</Grid>
{*/ Remaining Field */}
<Button type="submit" name="submitButton">
Submit
</Button>
</Form>
)}
</Formik>
</Box>
);
};
PUT API:
const handleFormSubmit = (
data: UserData,
imageFile: File | null,
setSubmitting: (isSubmitting: boolean) => void
) => {
setSubmitting(true);
const formData = new FormData();
if (imageFile) {
formData.append('ProfileImage', imageFile);
}
formData.append('Id', '5eb37003-6923-4939-5241-08dbd3b53cb0');
// eslint-disable-next-line no-debugger
debugger;
formData.append('Username', '[email protected]');
formData.append('Email', '[email protected]');
formData.append('PhoneNumber', data.phone);
// formData.append('BirthDay', data.dob.toISOString());
formData.append('BirthDay', '2023-10-02T19:00:00');
formData.append('Website', data.website);
// formData.append('Company', data.company);
// formData.append('Country', data.country);
formData.append('FullName', data.fullName);
formData.append('Language', data.language);
formData.append('TimeZone', data.timeZone);
formData.append('Currency', data.currency);
// formData.append('Description', data.description);
// Append other form fields to formData
// eslint-disable-next-line no-debugger
debugger;
const token = localStorage.getItem('token');
axios
.put('https://admin.accountsdash.com/api/User/account', formData, {
headers: {
accept: '*/*',
'Content-Type': 'multipart/form-data',
Authorization: `Bearer ${token}`,
},
})
.then((response) => {
console.log('User data updated:', response.data);
})
.catch((error) => {
if (error.response) {
console.error('Error updating user data:', error.response.data);
} else {
console.error('Network error:', error.message);
}
})
.finally(() => {
setSubmitting(false);
});
};
任何帮助将不胜感激。 谢谢你
initialValues
仅在第一次渲染期间设置,其中尚不存在数据。
您可以尝试使用
setInitialFieldValues
以及根据 文档从 API 获得的值,而不是使用
resetForm
在 useEffect 中设置值