我的代码是:
state = { keyItems: [], urlItems: [] }
componentDidMount() {
Storage.list('')
.then(keyItems => {
console.log("keyItems: ", keyItems)
this.setState({ keyItems: keyItems })
/*for each photo key in the folder..*/
keyItems.forEach(function(keyItem) {
/*get the URL*/
Storage.get(keyItem.key)
.then(urlItem => {
console.log("urlItem: ", urlItem)
/*add URL item to state*/
/*ANY CALL TO this.setState HERE DOESN'T WORK, i've tried
even simple tests*/
this.setState(prevState => ({ urlItems:[...prevState.urlItems, { key: keyItem.key, source: urlItem } ]}))
})
.catch(err => {
console.log("error fetching photo URL", err)
})
})
})
.catch(err => {
console.log("error fetching photos keys", err)
})
}
谢谢!
this
的值迷路.then
内
你可以试试这个
this
一个变量this
的这在码
componentDidMount () {
const that = this;
// now call setState like this
that.setState(...)
}
您可以通过以下链接阅读更多关于它,但是我在这里把它的一般要点。
this
总是方法被调用的对象。然而,传递方法then()
的时候,你是不是调用它!该方法将存储在某个地方,并从那里以后调用。
Why is 'this' undefined inside class method when using promises?