javascript - React 状态已设置,但在渲染时看起来它是空的

标签 javascript reactjs render state

  1. 从 Dropbox 调用 API
  2. 将response中的数据进行过滤,使用map存储到数组中。
  3. 将数组设置为状态
  4. 在渲染时使用它

所以这基本上就是我正在尝试做的事情 - 尝试使用 Dropbox API 制作照片库 - 我相信我成功地排在第 3 位,因为当我 console.log 数组状态时,它会显示内容。但是,当我尝试打印它的长度时,它显示为 0,我什至无法在渲染时使用它 - 它显示为 undefined object 。

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

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 时的开发工具

Devs tools when I did console.log

最佳答案

您遇到异步代码问题。当您设置状态时,数组为空。您可以使用 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 });
    })
}

关于javascript - React 状态已设置,但在渲染时看起来它是空的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45959943/

相关文章:

javascript - 使用 javascript 获取字符串拆分后的剩余部分

javascript - 如何正确转义正则表达式中的字符

javascript - 将列与屏幕中心对齐

javascript - 如何在react中渲染嵌套数组

reactjs - 为什么状态管理库使用 React 的上下文来进行依赖注入(inject)?

reactjs - 在 url 更改时重新渲染组件

javascript - 按位运算在运行时容易失败 typescript

javascript - npm:安装和使用包的不同版本

Java LWJGL FPS 越来越差

java - 如何将列表呈现为模板?