首页 > 解决方案 > 为什么不将 URL 放在状态数组中?

问题描述

我正在尝试将用户上传的图像 URL 放入一个数组中,然后在视图中显示该图像。使用我的代码,我得到的只是[]控制台中的一个空白。为什么没有任何图像 URL 进入数组,然后在我的视图中显示该图像?

JS 状态和函数

this.state = {
            selectedFile: null,
            previewImgURL: '',
            pictures: []
        };
        this.imageUpload = this.imageUpload.bind(this);
}

imageUpload(e) {
        let reader = new FileReader();
        let file = e.target.files[0];

        reader.onloadend = () => {
            this.setState({
                selectedFile: file,
                previewImgURL: reader.result,
                pictures: [...this.state.previewImgURL, this.state.previewImgURL]
            });
        };

        if (file) reader.readAsDataURL(file); // Allows user to preview image uploaded

        this.setState(() => ({file}));
        console.log(this.state.pictures); // in console, all I get's an empty []
    }

JSX 代码:

    <div className="inputWrapper">
                    <input
                        id="new_post_image"
                        name="post_image"
                        className="button is-success is-outlined"
                        type="file"
                        style={{display: 'none'}}
                        onChange={this.imageUpload}
                        accept="image/*"
                    />
                    <label className="button is-success is-outlined" htmlFor="new_post_image">Upload</label>
                </div>

                {
                    this.state.pictures.map(key => (
                        <div className="uploaded-pics">
                            <Feed src={this.state.previewImgURL[key]} key={key} />
                        </div>
                    ))
                }
</div>

这是 Feed.js:

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

const feed = (props) => {
    return (
        <div className="row">
            <div className="col-md-6 col-sm-6">
                <img src={props.src}/>

            </div>
        </div>
    );
};

export default feed;

标签: javascriptreactjsdebugging

解决方案


我认为问题在于您实际上将图片添加到状态中。 this.setState({ selectedFile: file, previewImgURL: reader.result, ----> pictures: [...this.state.previewImgURL, this.state.previewImgURL] });

当您使用扩展运算符时,您实际上还this.state没有,所以this.state.previewImgURL还不存在。

我会尝试:

this.setState({
  selectedFile: file,
  previewImgURL: reader.result,
  pictures: [reader.result]
});

我也不确定...在该上下文中使用(传播)语法。如果您只想更新状态的图片部分(假设您已经拥有状态),您可以将其用作:

this.setState({
  ...this.state,
  pictures: [reader.result]
});

另一件值得注意的事情是您正在更新回调中的状态,因此当您调用您的console.log(this.state.pictures)

此外,您处于同一个周期内,因此您的状态尚未更新。

如需额外调试,请在 Chrome DevTools 中的某处和控制台类型中放置某种调试器this.state.picture。这将显示状态的图片部分,并且在调试器中您还可以单步执行您的程序。转到此处了解有关 DevTools 调试的更多信息:https ://developers.google.com/web/tools/chrome-devtools/javascript/


推荐阅读