我正在使用 React Native。我已经查看过什么是未处理的承诺拒绝?,但我根本无法理解。
当我创建组件时:
render(){
const MenuComponent = (
<MenuScreen CloseSlideMenu={this.SlideMenu.CloseSlideMenu} />
)
...
}
我收到以下错误:
'可能的未处理的承诺拒绝(id:0)类型错误:未定义是 不是一个函数(评估 '_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>
)
}
有人可以向我解释为什么我会遇到这个错误吗?我该如何解决这个问题?
有几件事是错误的。您将布尔值与
this
绑定为函数的 .bind(true)
上下文。
您还在函数声明中使用
.catch()
。 .then()
和 .catch()
用于函数调用。
此外,如果这是函数的初始声明,则您在声明它之前尝试对其进行
.bind()
。您需要先声明它。
我建议您阅读 MDN 上的 .bind() 和 Promise。
这里有一个小例子,希望能帮助您理解这些原则:
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>
);
}
};
由于不同的原因,我遇到了类似的错误:使用 useContext 从上下文文件导入异步函数“myFunc”。
我的错误:未处理的 Promise Rejection 不是一个函数,而是一个 Promise 的实例。
const {
state: { some, stuff }, myFunc,
} = useContext(SomeContext);
当调用不带参数/变量的“myFunc”时,不要包含括号。 将
const output = await myFunc();
更改为 const output = await myFunc;
为我解决了这个问题。