我的代码是:
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)
})
}
谢谢!
答案 0 :(得分:1)
body, html {background-color: #fff; margin: 0; padding: 0;}
table {border-collapse: collapse;}
td {border: #aaa dashed 2px; height: 3.3in; padding: .1in; vertical-align: top; width: 2.3in;}
span {font-family: Arial; font-size: 24px;}
@media footer {tbody {page-break-after: right; break-after: right;}}
的值在this
内部丢失了
您可以尝试
.then
设置为变量this
在代码中显示
this
您可以在下面的链接中了解更多信息,但是我将其要点放在这里。
componentDidMount () { const that = this; // now call setState like this that.setState(...) }
始终是调用该方法的对象。但是,当 将方法传递给this
时,您没有调用它!方法 将存储在某个地方,稍后再从那里调用。
Why is 'this' undefined inside class method when using promises?