首页 > 解决方案 > react - 上传图片并将上传路径 URL 附加到数据库条目

问题描述

使用 react/redux 工具包

我有一个项目创建屏幕,它上传项目的图像,然后在我的数据库中为该项目创建一个条目。

数据库值之一是 imageURL,它应该指向最近上传的图像。

我有一个有状态的 imageURL 值,应该在文件上传后但在分派创建数据库条目之前将其更改为正确的路径,但我无法在分派发生之前设置 imageURL。

我已经尝试过 useEffect 和 async 但它的 imageURL 似乎只在调度后设置。

const [imageURL, setImageURL] = useState('');

  //File upload handler
  const uploadFileHandler = async (file) => {
    const formData = new FormData();
    formData.append('image', file);
    setUploading(true);
    try {
      const config = {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      };
      const fileURL = await axios.post('/api/upload', formData, config);
      setUploading(false);
      return fileURL.data; //this is the path of the uploaded file
    } catch (error) {
      console.error(error);
      setUploading(false);
    }
  };

  //TODO: Submit handler
  const submitHandler = async (e) => {
    e.preventDefault();
    let path = await uploadFileHandler(uploadFile); //this should give me the URL from the upload
    setImageURL(path); //this should set the Image URL to the above value, but does not
    dispatch(createItem(data, headers));
  };

如果有人知道如何解决这个问题,我将不胜感激。

谢谢

标签: reactjsmongooseredux-toolkit

解决方案


它不会起作用,因为setImageURL并且dispatch在相同的功能上。发生的情况是它首先在设置图像 URL 之前完成该功能。

您可以做的是将其作为“数据”插入到调度中,例如:

 const submitHandler = async (e) => {
    e.preventDefault();
    let path = await uploadFileHandler(uploadFile);
    dispatch(createItem({
       ...data,
       image_url: path, // idk if this is the correct property name on the data
    }, headers));
  };

或者使用useEffect钩子:

 const submitHandler = async (e) => {
    e.preventDefault();
    let path = await uploadFileHandler(uploadFile);
    setImageURL(path);
  };

  useEffect(() => {
     if (imageURL !== '') {
        dispatch(createItem(data, headers));
     }
  }, [imageURL]);

如果 imageURL 发生变化,这种方式将触发调度。


推荐阅读