React:用户选择的图片与来自 res.data 的结果不同

问题描述

我正在创建一个组件,该组件将使用 react js 和 multer 创建带有描述和图像的帖子。问题是我选择的一些图像已被删除并用相同的图像替换两次。我已经使用控制台日志检查了代码,结果很好,但是在 axios 发布请求后,图像列表发生了变化。你能帮我解释一下为什么会发生这种事情吗?

createPost.js
const UserPost = ({ userData }) => {
  const { username: usernameProps } = userData;

  const [postInfo,setPostInfo] = useState({
    username: '',description: '',postimageCollection: '',});

  useEffect(() => {
    setPostInfo({ username: usernameProps });
  },[usernameProps]);

  const dispatch = usedispatch();
  const classes = UseStyles();

  const handlePost = async (e) => {
    e.preventDefault();

    const fData = new FormData();
    for (let i = 0; i < postimageCollection.length; i++) {
      fData.append('postimageCollection',postimageCollection[i]);
      **console.log('postimageCollection',postimageCollection[i]); <-- here the list of images is correct**
    }

    try {
      await axios({
        method: 'POST',url: 'http://localhost:5000/user/posts',data: fData,headers: {
          'content-type': 'multipart/form-data',},}).then((res) => {
        **console.log(res.data); <-- this is where the list of images changes**
        // setPostInfo((prevImgCollection) => ({
        //   ...prevImgCollection,//   postimageCollection: res.data,// }));
      });
    } catch (error) {
      console.log(error.response);
    }
    dispatch(createPost(postInfo));
  };

  const handleChangeImageCollection = (e) => {
    const newArray = [...postimageCollection];
    for (let i = 0; i < e.target.files.length; i++) {
      newArray.push(e.target.files[i]);
    }

    setPostimageCollection(newArray);
    if (newArray.length > 5) {
      setCurrentimageHide('+' + (newArray.length - imagePerPost));
    }
  };

  const handleChange = (e) => {
    const { name,value } = e.target;
    setPostInfo((prev) => ({ ...prev,[name]: value }));
  };

  const indexOfLastimage = currentimagePost * imagePerPost;
  const indexOfFirstImg = indexOfLastimage - imagePerPost;
  const currentimage = postimageCollection.slice(
    indexOfFirstImg,indexOfLastimage
  );

  return (
    <Container
      component='div'
      className={classes.userPostContainer}
      style={{ padding: '0',margin: '0' }}
    >
      <Card className={classes.userPostCard} style={{ BoxShadow: 'none' }}>
        <CardContent style={{ padding: '0 0 1.5em 0' }}>
          <form novalidate onSubmit={handlePost}>
            <Grid container>
              <Grid item xs={12}>
                <TextField
                  variant='outlined'
                  id='description'
                  name='description'
                  type='text'
                  value={postInfo.description}
                  onChange={handleChange}
                  placeholder={`What's on your mind,${
                    userData && userData.username
                  }`}
                  fullWidth
                  InputLabelProps={{
                    classes: {
                      root: classes.label,focused: classes.focused,}}
                  InputProps={{
                    className: classes.textfieldBg,classes: {
                      root: classes.cssOutlinedInputBg,focused: classes.cssFocused,notchedOutline: classes.NonotchedOutline,}}
                />
              </Grid>
              <Grid
                xs={12}
                container
                className={classes.postPhotoContainer}
                style={{ padding: '0' }}
              >
                <Grid xs={12}>
                  <ImageList
                    postimageCollection={currentimage}
                    currentimageHide={currentimageHide}
                  />
                </Grid>
                <Grid xs={10}>
                  <input
                    accept='image/*'
                    id='postimageCollection-file-button'
                    type='file'
                    name='postimageCollection'
                    onChange={handleChangeImageCollection}
                    multiple
                  />
                  <label htmlFor='postimageCollection-file-button'>
                    <ImageIcon />
                    Add Photo
                  </label>
                </Grid>
                <Grid
                  xs={2}
                  style={{
                    padding: '0',margin: '0',display: 'flex',justifyContent: 'center',}}
                >
                  <Button
                    type='submit'
                    variant='contained'
                    startIcon={<SendIcon />}
                  >
                    Post
                  </Button>
                </Grid>
              </Grid>
            </Grid>
          </form>
        </CardContent>
      </Card>
    </Container>
  );
};

正确的输出

0: "http://localhost:5000/public/images/post/postimageCollection-1616065863529.jpg" 1:“http://localhost:5000/public/images/post/postimageCollection-1616065863529.jpg” 2:“http://localhost:5000/public/images/post/postimageCollection-1616065863530.jpg”

错误输出

0: "http://localhost:5000/public/images/post/postimageCollection-1616065863529.jpg" 1:“http://localhost:5000/public/images/post/postimageCollection-1616065863529.jpg” 2:“http://localhost:5000/public/images/post/postimageCollection-1616065863530.jpg”

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)