[英]Possible unhandled promise rejection in react-native
我正在使用以下代碼,產生“可能的未處理的承諾拒絕”:
constructor(props){
super(props)
DatabaseHandler.getInstance().getItems(function (items) {
console.log(items)//successfully print data
this.setState({inventoryArray: items}).bind(this)//causing error
})
}
但是,以下代碼成功運行並在日志中打印響應:
constructor(props){
super(props)
DatabaseHandler.getInstance().getItems(function (items) {
console.log(items)//Successfully print data
})
}
如何解決這個錯誤?
通常,在組件的constructor
中進行異步調用是一個壞主意。 相反,我建議您按以下方式從componentDidMount
進行這些調用
class MyComponent extends React.Component {
componentDidMount() {
DatabaseHandler.getInstance().getItems(function (items) {
console.log(items)//Successfully print data
this.setState({ inventoryArray: items });
});
}
}
在官方的React文檔中更多關於如何使用
constructor
的信息
你也可以刪除bind
,並使用箭頭功能,因此this
保持在組件的上下文。
constructor(props) {
super(props)
DatabaseHandler.getInstance().getItems((items) => {
console.log(items)//successfully print data
this.setState({inventoryArray: items})
})
}
另外,您的.bind(this)
在錯誤的位置。 它應該放在外部}
(關閉function
)
constructor(props) {
super(props)
DatabaseHandler.getInstance().getItems(function (items) {
console.log(items)
this.setState({inventoryArray: items})
}.bind(this)) // bind should come here
}
但是,在構造函數中發出api請求是一種錯誤的模式。 ReactJS Docs提到了componentDidMount
是推薦這樣做的地方。
class YourComponent extends React.Component {
constructor(props) {
super(props)
this.state = {
inventoryArray: [],
}
}
componentDidMount() {
DatabaseHandler.getInstance().getItems((items) => {
console.log(items)//successfully print data
this.setState({inventoryArray: items})
})
}
}
進行以下更改可以解決此問題:
constructor(props) {
super(props)
this.onGetInventories = this.onGetInventories.bind(this)
//Loading inventory list from server
DatabaseHandler.getInstance().getItems(this.onGetInventories)
}
onGetInventories(items) {
console.log(items)
this.setState({inventoryArray: items})//Works
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.