简体   繁体   English

为什么我不能用用户的URL填充数组?

[英]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. 我想用URL填充数组,但也要一一显示这些URL。 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. 本质上,我只希望能够在<Feed/>组件中动态创建<img/>标签,以使用户联机并上传文件,然后放入数组。

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 至少Feed应该在pictures数组上进行迭代

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. 我已经使用react钩子简化了事情,也使用了一些ES6的东西,例如胖箭头功能。 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 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. 就像我在评论中说的那样,如果您希望跨不同的用户使用它,则必须使用数据库之类的东西来存储到数据库的链接,并使用一种方法来检索它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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