- 从 Dropbox 调用 API
- 将response中的数据进行过滤,使用map存储到数组中。
- 将数组设置为状态
- 在渲染时使用它
所以这基本上就是我正在尝试做的事情 - 尝试使用 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 时的开发工具
最佳答案
您遇到异步代码问题。当您设置状态时,数组为空。您可以使用 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/