Loading images from Firebase Realtime Database + S

2019-07-23 04:27发布

问题:

I'm creating something like an image gallery of cars using create-react-app in Firebase documentation (react+redux+firebase). Images information are stored in Firebase Realtime Database, but the actual image files are stored in Firebase Storage. In componentWillMount, I called an action creator to fetch those images:

this.props.fetchCars();

In the action creator, this function executes:

export function fetchCars() {
  return (dispatch, getState) => {
         carsRef.on('value', snapshot => {
          dispatch({
              type: FETCH_CARS,
              payload: snapshot.val()
          });
      });
  };
}

That dispatch goes to my reducer and update the state accordingly. My state looks like this:

{
cars: {
  make: "Toyota",
  model: "Vios",
  year: 2015,
  fileName: "cars1.jpg",
  fileFullPath: ""
  }
}

After fetching, the full URL of the image is not yet known (fileFullPath), as fileName is just a file name uploaded by the user. So I have to use Firebase Storage to get the downloadable Url so I can put it in an <img /> tag:

export function getFileFullPath(){
    return (dispatch, getState) => {
     var newState = Object.assign({}, getState());
     var imgRef, carUrl;
     _.map(newState.cars, (car, index) => {
       imgRef = storageRef.child('images/'+car.img);
       carUrl = imgRef.getDownloadURL().then( url => {
            car.fileFullPath=url;
       });
     });

     dispatch({
         type: FILL_UP_URL,
         payload: newState.cars
     });
    };
}

However, when I run this, it doesn't work. After 1st dispatch, the images list were retrieved correctly from Realtime Database with empty fileFullPath. After 2nd dispatch it is still empty. I guess there's something wrong with the way I do this, but I don't know how to do it.