首页 > 解决方案 > 未存储 URL 的 React Firestore 图像数组

问题描述

class App extends React.Component {
  constructor(props) {
    super(props);
    this.addData = this.addData.bind(this);
    this.state = {
      username: "",
      imgFile: [],
      imgUrl: [],
    };
  }
  upload = (e) => {
    e.preventDefault();

    this.storeImageAndgetUrl(this.addData);
  };
  storeImageAndgetUrl = (addData) => {
    const imgUrl = [];
    const storage = fire.storage();
    const ref = storage.ref();
    this.state.imgFile.forEach((file) => {
      ref
        .child(file.name)
        .put(file)
        .then(
          (snapShot) => {
            console.log(snapShot);
            const storage = fire.storage();

            this.state.imgFile.forEach((file) => {
              const ref = storage.ref(file.name);
              ref.getDownloadURL().then((fireBaseUrl) => {
                console.log(fireBaseUrl);
                imgUrl.push(fireBaseUrl);
              });
            });
            this.setState({ imgUrl });
          },
          (err) => {
            console.log(err);
          }
        );
    });
    addData();
  };
  addData = () => {
    // const images = this.state.imgUrl;
    console.log(this.state.imgUrl);
    fire.firestore().collection("new").add({
      name: this.state.username,
      img: this.state.imgUrl,
    });
  };
  handleChangeUsername = (e) => {
    this.setState({ [e.target.name]: e.target.value });
  };
  setImage = (e) => {
    if (Array.from(e.target.files[0]).length < 4) {
      const img = Array.from(e.target.files);
      this.setState({ imgFile: img });
    } else {
      alert("You can select maximum 5 Images");
    }
  };
  render() {
    console.log(this.state.username);
    console.log(this.state.imgFile);
    console.log(this.state.imgUrl);
    return (
      <div className="App">
        <form onSubmit={this.upload}>
          <label>Username:</label>
          <input
            type="text"
            value={this.state.username}
            name="username"
            onChange={this.handleChangeUsername}
          />
          <input
            type="file"
            accept="image/*"
            onChange={this.setImage}
            multiple
          />
          <button type="submit">Submit</button>
        </form>
      </div>
    );
  }
}

export default App;

在上面的代码中,我存储了多个图像数组,并使用回调获取这些图像的 URL,并将 URL 存储在 firestore 中。未存储 URL 的图像数组。我已经创建了一个回调函数,我在其中存储图像和另一个函数,其中 Fetched URL Array 存储在 firestore

标签: javascriptarraysreactjsfirebasegoogle-cloud-firestore

解决方案


推荐阅读