问题
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 storage = fire.storage();
    const reference = storage.ref();
    this.state.imgFile.forEach((file) => {
      reference
        .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) => {
                  this.setState((prevState) => ({
                    imgUrl: [...prevState.imgUrl, fireBaseUrl],
                  }));
                },
                () => {
                  addData();
                }
              );
            });
          },
          (err) => {
            console.log(err);
          }
        );
    });
  };
  addData = () => {
    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>
        {/* <ZoomImage /> */}
        {/* <ExamplePdfViewer /> */}
      </div>
    );
  }
}
export default App;
In the above code, I'm using callback function on submit of form to store and fetch the image and URL for storing multiple image files in array and storing it in firestore database. And If i select 2 images, on click submit it stores all those 2 images but stores the array of only one image URL. How to rectify it?
来源:https://stackoverflow.com/questions/62848171/react-firebase-multiple-images-select-on-submit-storing-only-one-image-url-in-ar