【问题标题】:react - upload image and attach upload path URL to database entryreact - 上传图片并将上传路径 URL 附加到数据库条目
【发布时间】:2021-06-07 11:49:09
【问题描述】:

使用 react/redux 工具包

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

其中一个数据库值是 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));
  };

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

谢谢

【问题讨论】:

  • 什么是setImageURL?是useState setter 还是 redux 操作?如果它是一个 redux 操作,你有什么理由不调用 dispatch 吗?
  • 哦,对不起,在我的代码复制/粘贴中遗漏了。这是一个二传手:const [imageURL, setImageURL] = useState('');
  • 看起来应该可以了。 “这应该将图像 URL 设置为上述值,但没有”是什么意思?您希望它在哪里看到和看不到?
  • 感谢您的帮助,在下面回答。

标签: reactjs mongoose redux-toolkit


【解决方案1】:

它不会起作用,因为setImageURLdispatch 在同一个函数上。发生的情况是它首先在设置图像 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发生变化,这种方式会触发dispatch。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-22
    • 2013-11-01
    • 2015-04-20
    • 2023-04-09
    • 2020-11-30
    相关资源
    最近更新 更多