【问题标题】:React state is set but it looks like it's empty when rendering反应状态已设置,但在渲染时它看起来像是空的
【发布时间】:2018-02-08 03:21:57
【问题描述】:
  1. 从 Dropbox 调用 API
  2. 从响应中过滤数据并使用映射将其存储到数组中。
  3. 将数组设置为状态
  4. 在渲染时使用它

所以这基本上是我想要做的 - 尝试使用 Dropbox API 制作照片库 - 我相信我成功了第 3 位,因为当我 console.log 数组状态时,它会显示内容。但是,当我尝试打印它的长度时,它显示为 0,我什至无法在渲染时使用它 - 它显示为未定义的对象。

我会附上开发工具的代码和图片。请帮我! :(

JS 文件

let dbx = new Dropbox();    

class Thumbnails extends Component {
    constructor(props) {
        super(props);
        this.state = {
            thumbnails: []
        };
    }

    componentDidMount() {
        let thumbnailsArray = [];
        this.props.travel.map(file => {
            dbx.filesGetTemporaryLink({ path: file })
            .then(res => {
                thumbnailsArray.push(res.link);
            });
        });
        this.setState({ thumbnails: thumbnailsArray });
    }

    render() {
        console.log(this.state.thumbnails);
        console.log(this.state.thumbnails.length);
        console.log(this.state.thumbnails[5]);
        if (this.state.thumbnails.length < 1) {return <p>Loading...</p>}
        return(
            <table id="thumbnails">
                <tbody>
                    <tr>
                        <td src={{backgroundImage: `${this.state.thumbnails[5]}`}}></td>
                        {this.state.thumbnails.map(thumbnail => {
                            return (<td style={{backgroundImage: `${thumbnail}`}}></td>);
                        })}
                    </tr>
                </tbody>
            </table>
        );
    }


}

运行 console.log 时的开发工具

【问题讨论】:

  • 在异步回调响应中移动 setState

标签: javascript reactjs render state


【解决方案1】:

您对异步代码有疑问。当您设置状态时,数组为空。您可以使用Promise.all 等待所有请求完成,然后再设置新状态。

componentDidMount() {
    Promise.all(this.props.travel.map(file => {
        return dbx.filesGetTemporaryLink({ path: file })
          .then(res => res.link);
    })).then(thumbnailsArray => {
      this.setState({ thumbnails: thumbnailsArray });
    })
}

【讨论】:

    猜你喜欢
    • 2022-07-22
    • 2019-02-21
    • 1970-01-01
    • 2021-11-20
    • 1970-01-01
    • 2021-01-17
    • 2019-11-19
    • 2020-01-18
    • 2019-01-19
    相关资源
    最近更新 更多