微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决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 举报,一经查实,本站将立刻删除。