我正在处理一个使用 HOC 接受输入(来自用户的多个图像和文本(的表单。 下面是我的表单组件。
import React from "react";
import Grid from "@material-ui/core/Grid";
import Typography from "@material-ui/core/Typography";
import Alert from "@material-ui/lab/Alert";
import TextField from "@material-ui/core/TextField";
import FormControlLabel from "@material-ui/core/FormControlLabel";
import { Snackbar, IconButton } from "@material-ui/core";
import { Loading, Snackbars, UIButton, UITextField } from "../UI/index";
import {
Paper,
makeStyles,
Button,
} from "@material-ui/core";
function Gallery(props) {
let {
submitHandler,
selectImages,
message,
galleryForm,
inputChangedHandler,
} = props;
return (
<div>
<Paper
elevation={3}
style={{ padding: "20px" }}
>
<form
onSubmit={submitHandler}
noValidate
id="galleryForm"
>
<Grid container spacing={3}>
<Grid item xs={12} md={6}>
<UITextField
name="imageTitle"
label="Image Title"
value={galleryForm.imageTitle.value}
onChange={(event) => inputChangedHandler(event, "imageTitle")}
error={galleryForm.imageTitle.invalid}
helperText={galleryForm.imageTitle.helperText}
/>
</Grid>
<Grid item xs={12} sm={6}>
<Grid container>
<Grid>
<TextField
id="standard-basic"
fullWidth
label="Select File To Upload"
value={message}
error={galleryForm.images.invalid}
helperText={galleryForm.images.helperText}
/>
</Grid>
<Grid>
<input
accept=".jpg , .png, .jpeg"
className={classes.input}
style={{ display: "none" }}
id="raised-file"
multiple
type="file"
onChange={selectImages}
/>
<label htmlFor="raised-file">
<Button
variant="contained"
style={{
background: "#D3D3D3",
color: "black",
fontSize: "15px",
borderRedius: "4px",
}}
component="span"
>
UPLOAD PHOTOS
</Button>
</label>
</Grid>
</Grid>
</Grid>
<Grid className={classes.center}>
<UIButton
type="submit"
variant="contained"
color="primary"
size="large"
className={classes.submit}
>
create gallery
</UIButton>
</Grid>
</Grid>
</form>
</Paper>
</div>
);
}
export default enhancer(Gallery);
下面是我的 HOC(增强器(,它采用图库组件
import React, { useEffect, useState } from "react";
import { compose } from "redux";
import Gallery from "./index";
import galleryFiled from "./galleryField";
export let enhancer = compose((Gallery) => ({ ...props }) => {
const [galleryForm, setGalleryForm] = useState(galleryFiled);
const [message, setMessage] = useState("");
const selectImages = (event) => {
const updatedForm = {
...galleryForm,
};
console.log("check:", galleryForm);
for (var i = 0; i < event.target.files.length; i++) {
if (event.target.files.item(i).name.match(/.(jpg|jpeg|png)$/)) {
updatedForm.images.value.push(event.target.files.item(i));
}
}
setGalleryForm({ ...updatedForm });
let message = `${updatedForm.images.value.length} valid image(s) selected`;
console.log(galleryForm);
setMessage(message);
};
const inputChangedHandler = (event, inputIdentifier) => {
const updatedForm = {
...galleryForm,
};
console.log(updatedForm);
updatedForm[inputIdentifier].value = event.target.value;
updatedForm[inputIdentifier].invalid = false;
updatedForm[inputIdentifier].helperText = "";
console.log(updatedForm);
setGalleryForm({
...updatedForm,
});
console.log(galleryForm);
};
const clearForm = (event) => {
let allFormKeys = Object.keys(galleryForm);
let formData = { ...galleryForm };
allFormKeys.forEach((formKey) => {
if (formKey == "images") {
formData[formKey].value = [];
formData[formKey].invalid = false;
formData[formKey].helperText = "";
} else {
formData[formKey].value = "";
formData[formKey].invalid = false;
formData[formKey].helperText = "";
}
});
setMessage("");
setGalleryForm(formData);
};
const submitHandler = (event) => {
event.preventDefault();
console.log("submit", galleryForm);
let updatedForm = { ...galleryForm };
console.log("update", updatedForm);
console.log("final form", galleryForm);
clearForm();
};
return (
<Gallery
{...props}
{...{
submitHandler,
selectImages,
message,
galleryForm,
inputChangedHandler,
}}
/>
);
});
export default enhancer;
因此,每当我首先单击上传图像按钮时,我都会使用图库表单的临时副本,然后在使用选择图像按钮函数中的 useState 钩子将正确的文件更新到图库表单后。
所以我的问题是,当我最初打印画廊的临时副本从它的打印更新的画廊形式,即使我在功能的后期更新我的表单。
我在使用submitHandle函数时遇到的相同问题,clearForm函数即使我最后一次调用函数也会更新图库Form,因此即使在最初打印galleryForm之后,我也丢失了表单数据并获得了空表单。
你正在使用spreadSyntax来克隆你的galleryForm,但是你必须注意,spread语法只制作对象的浅拷贝。新对象中的嵌套值仍然共享引用,当您尝试更新嵌套值时,get也会反映在原始状态中
正确的更新方法是在每个嵌套级别克隆值,如下所示
const selectImages = (event) => {
console.log("check:", galleryForm);
const imagesValue = [];
for (var i = 0; i < event.target.files.length; i++) {
if (event.target.files.item(i).name.match(/.(jpg|jpeg|png)$/)) {
imagesValue.push(event.target.files.item(i));
}
}
// Update nested state
setGalleryForm(prevGalleryForm => ({
...prevGalleryForm,
images: {
...prevGalleryForm.images,
value: prevGalleryForm.images.concat(imagesValue)
}
}));
let message = `${imagesValue.length} valid image(s) selected`;
console.log(galleryForm);
setMessage(message);
};
const inputChangedHandler = (event, inputIdentifier) => {
const updatedForm = {
...galleryForm,
[inputIdentifier]: {
...galleryForm[inputIdentifier],
value: event.target.value,
invalid: false,
helperText:"",
}
};
console.log(updatedForm);
setGalleryForm(updatedForm);
console.log(galleryForm);
};
const clearForm = (event) => {
let allFormKeys = Object.keys(galleryForm);
let formData = { ...galleryForm };
allFormKeys.forEach((formKey) => {
if (formKey == "images") {
formData[formKey].value = [];
formData[formKey].invalid = false;
formData[formKey].helperText = "";
} else {
formData[formKey].value = "";
formData[formKey].invalid = false;
formData[formKey].helperText = "";
}
});
setMessage("");
setGalleryForm(formData);
};