简体   繁体   中英

How to use Object.key.map() in ReactJS?

I am studying ReactJS, and making a website with it and Firebase.

I wanted to display all images in my Firebase Stroage, but I don't know how to do that, and my code does't work.

I got the all url of images in Firebase Storage, and put these into array. when I console.log(imageObejct), it shows all links correctly.

But my render (object.key.map) doesn't work.

I tried different ways, but didn't work.

Help!

I have tried 1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Description

  1. https://flaviocopes.com/react-how-to-loop/
class ImageUpload extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            image: [],
            user: this.props.user,
            url: '',
            progress: 0,
            dialog: false,
            fileName: '',
            file: '',
            imagePreviewUrl: '',
            title: '',
            content: '',
            imagePath: [],
            imageObject: ''
        };

////////////////////////////////////////////////////////
 displayImage = (images) => {

        // Get the download URL

        images.getDownloadURL().then(data => {
            // Insert url into an <img> tag to "download"
            this.setState({ imageObject : [(this.state.imageObject == null) ? null : data] })

           // console.log(this.state.imageObject)
        }).catch(error => {
//////////////////////////////////////////
    render() {
        const { classes } = this.props;
        return (
             <div>
                {Object.keys(this.state.imageObject).map(id => {
                    const img = this.state.imageObject[id];
                    return (
                        <Card key={id}>
                            <CardContent>
                                <Typography>
                                    Title: 
             ///here!!//              <img src={img}/>
                                </Typography>




I expected all images in my Firebase Storage

but it just shows me only one(first one) image out of 12.

Firstly set your imageObject to empty array as default, if it is an array (probably it'd be named imageArray then):

 this.state = {
   imageObject: []
 };

Then in your setState , add the data to your array

 images.getDownloadURL().then(data => {
   this.setState(state => ({
     imageObject: [...state.imageObject, data]
   }))
 })

After that when you render it, you don't need to use Object.keys , but just map the array:

 return (
    <div>
    {this.state.imageObject.map(img => {
     return (
//...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM