[英]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.