我正在使用 React Native。我已经查看了 What is an unhandled promise rejection? ,但我根本看不懂。
当我创建一个组件时:
render(){
const MenuComponent = (
<MenuScreen CloseSlideMenu={this.SlideMenu.CloseSlideMenu} />
)
...
}
我收到以下错误:
'Possible Unhandled Promise Rejection (id: 0) TypeError: undefined is not a function (evaluating '_this.OpenSlideMenu.bind(true).then(function() {}))'
this.OpenSlideMenu()
在 constructor()
中声明。
constructor (props, context) {
super(props, context)
this.OpenSlideMenu = this.OpenSlideMenu.bind(true).catch(function(e){
console.log("Promise Rejected");
});
this.CloseSlideMenu = this.CloseSlideMenu.bind(true).catch(function(e){
console.log("Promise Rejected");
});
}
this.drawer 在 render() 方法中声明:
render () {
const MenuComponent = (
<MenuScreen CloseSlideMenu={this.SlideMenu.CloseSlideMenu} />
)
return (
<Drawer
ref={(ref) => this.drawer = ref}
content={MenuComponent}
tapToClose={true}
openDrawerOffset={170}
stles={drawerStyles}
panCloseMask={0.2}
closedDrawerOffset={-3}
styles={drawerStyles}
tweenHandler={(ratio) => ({
main: { opacity: (2-ratio)/2 }
})}>
<GroceryScreen selectedCategory='Todos' OpenSlideMenu={this.OpenSlideMenu} />
</Drawer>
)
}
有人可以向我解释为什么会出现此错误吗?我该如何解决这个问题?
最佳答案
一些错误。您使用 .bind(true)
将 bool 值绑定(bind)为函数的 this
上下文。
您还在函数声明中使用了 .catch()
。 .then()
和 .catch()
用于函数调用。
此外,如果这是函数的初始声明,您将尝试在它被声明之前 .bind()
到它。您需要先声明它。
我建议您阅读 .bind()和 Promise在 MDN 上。
这里有一个小例子,希望能帮助您理解这些原则:
class Demo extends PureComponent {
constructor( props ) {
// allow the user this in constructor
super( props );
// set default state
this.state = {
text: "Awaiting data..."
}
// only needed if used in a callback
this.method = this.method.bind( this );
}
componentDidMount() {
// calling the method that returns a promise when component mounts
this.method()
.then((res) =>{
// set state in a non-mutating way
this.setState({text: res});
});
}
// declaring a method to handle the api call
// yours will not be named method
method() {
return new Promise(
(resolve, reject) => {
// simulating network delay of 2 seconds ( lets hope not! )
setTimeout(() => {
resolve( "Data returned from promise" );
}, 2000 );
});
);
}
render() {
// destructure the text var from data
const { text } = this.state;
// return text
return (
<p>{ text }</p>
);
}
};
关于javascript - Possible Unhandled Promise Rejection undefined 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45246083/