简体   繁体   中英

Why can't I populate my array with the URL from the user?

I want to populate the array with URLs but also display those URLs one by one. For example, one user comes on, uploads a file, it gets stored in the array and displayed. The next user comes on, uploads a file, it gets stored in the array and displayed, etc.

Essentially, I just want to be able to create <img/> tags dynamically in the <Feed/> component for users to come online and upload files followed by getting placed into the array.

What am I doing wrong?

Inside Main components

this.state = {
   pictures: [],
   previewImgURL: ''
};

displayImage() {
    let pictures = this.state.pictures;
    let previewImgURL = this.state.previewImgURL;
    this.setState({pictures: [...previewImgURL, previewImgURL]});
    console.log(pictures);
    return <Feed src={pictures}/>;
};

render() {
   return(
      <div className="uploaded-pics">
        {this.displayImage()}
      </div>
   );
}

Inside Feed component

import React from 'react';
import './Feed.scss';

const feed = (props) => {
    return(
        <div className="parent">
            <img src={props.src} className="img-fluid" alt=""/>
        </div>
    );
};

export default feed;

At least the Feed should iterate over the pictures array

import React from 'react';
import './Feed.scss';

const feed = (props) => {
    return(
        <div className="parent">
            {props.src.map(item => 
                <img src={item} className="img-fluid" alt=""/>
            )}
        </div>
    );
};

export default feed;

This line

this.setState({pictures: [...previewImgURL, previewImgURL]});

probably should look like this

this.setState({pictures: [...pictures, previewImgURL]});

See if this code helps. I have used react hooks to simplify things, I have also use some ES6 stuff like fat arrow functions. And instead of an image upload I have used a simple input text with an "add" button (just for simulation)

https://codesandbox.io/s/frosty-microservice-2nev1

And here I am assuming this is for a single user. As I said in my comments, if you would want this to work across different users then you will have to use something like a database to store the links to the database and a method to retrieve it.

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