[英]Possible unhandled promise rejection in react-native
I'm using following code which produce "Possible unhandled promise rejection": 我正在使用以下代码,产生“可能的未处理的承诺拒绝”:
constructor(props){
super(props)
DatabaseHandler.getInstance().getItems(function (items) {
console.log(items)//successfully print data
this.setState({inventoryArray: items}).bind(this)//causing error
})
}
Though, following code runs successfully and prints response in log: 但是,以下代码成功运行并在日志中打印响应:
constructor(props){
super(props)
DatabaseHandler.getInstance().getItems(function (items) {
console.log(items)//Successfully print data
})
}
How to resolve this error? 如何解决这个错误?
Typically, its a bad idea to make asynchronous calls in the constructor
of the component. 通常,在组件的
constructor
中进行异步调用是一个坏主意。 Instead, I would recommend that you make these calls from the componentDidMount
as follows 相反,我建议您按以下方式从
componentDidMount
进行这些调用
class MyComponent extends React.Component {
componentDidMount() {
DatabaseHandler.getInstance().getItems(function (items) {
console.log(items)//Successfully print data
this.setState({ inventoryArray: items });
});
}
}
More about how to use the
constructor
in the official React docs在官方的React文档中更多关于如何使用
constructor
的信息
You could also remove bind
and use arrow function so this
keeps the context in your component. 你也可以删除
bind
,并使用箭头功能,因此this
保持在组件的上下文。
constructor(props) {
super(props)
DatabaseHandler.getInstance().getItems((items) => {
console.log(items)//successfully print data
this.setState({inventoryArray: items})
})
}
Also, your .bind(this)
is in the wrong place. 另外,您的
.bind(this)
在错误的位置。 It should be placed in the outer }
(where you close function
) 它应该放在外部
}
(关闭function
)
constructor(props) {
super(props)
DatabaseHandler.getInstance().getItems(function (items) {
console.log(items)
this.setState({inventoryArray: items})
}.bind(this)) // bind should come here
}
Making api requests in the constructor is a bad pattern though. 但是,在构造函数中发出api请求是一种错误的模式。 ReactJS Docs mentions that
componentDidMount
is the recommended place to do so. 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})
})
}
}
Making following changes solved this issue: 进行以下更改可以解决此问题:
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.