【问题标题】:Getting file from MaterialUI Upload Button to React Hook and uploading to Firestorage?从 MaterialUI 上传按钮获取文件到 React Hook 并上传到 Firestorage?
【发布时间】:2021-04-16 09:49:06
【问题描述】:

大家好,我正在使用 MaterialUI 的上传按钮:https://material-ui.com/components/buttons/

正如您在下面看到的,我已经复制粘贴了该按钮,现在我想使用我的钩子将其上传到 Firebase Firestorage。通过按下按钮它类 changeFoto

  <input
            accept="image/*"
            className={classes.input}
            id="contained-button-file"
            multiple
            type="file"
            onChange={(e) => changeFoto(e)}
          />
          <label htmlFor="contained-button-file">
            <Button className={classes.fotoButton} component="span">
              Foto
            </Button>
          </label>

这里可以看到changeFoto函数:

(setFoto 在本例中是一个钩子,而 foto 是 useState 的变量)

const changeFoto = (e) => {
    setFoto(e.target.files[0]);
    const pflegeengelRef = storage.child(
      "pflegeengel/" + pflegeengelDocumentIDs[selectedIndex]
    );
    pflegeengelRef.put(foto).then(function (snapshot) {
      console.log("Uploaded a file!");
    });
  };

当我查看存储有一个文件时,确实上传了一些东西。但这不是我的图像文件,它是一些奇怪的文件格式,其中只有“未定义”文本。所以我猜这是我的问题

【问题讨论】:

    标签: javascript reactjs react-hooks material-ui firebase-storage


    【解决方案1】:

    这是因为setFoto 是一个异步函数。它不会立即更新 foto - 它会触发以新的 foto 作为新值的渲染。

    当您尝试上传 foto 时,它尚未更新。使用put(e.target.files[0]) 可以解决您的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-21
      • 1970-01-01
      • 2019-01-29
      • 1970-01-01
      • 2011-04-11
      • 2022-10-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多