URL的React Firestore图像数组未存储

发布时间:2020-07-07 09:44
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的图像数组未存储。我做了一个回调函数,在其中存储图像,另一个函数在其中,将提取的URL数组存储在Firestore中

回答1