如何在React应用中使用承诺的功能 [英] How to use a promised function in a react app
问题描述
我正在尝试在React Web应用程序中实现 Bullet train API .根据他们的节点客户端文档,我设置了以下功能:
I'm trying to implement Bullet train API in a React web app. According to their node client documentation, I have setup the following function:
export const isFeatureEnabled = async (nameOfTheFeature) => {
return new Promise((resolve) => {
bulletTrain.init({
environmentID: BULLET_TRAIN_ENV_ID
});
bulletTrain.hasFeature(nameOfTheFeature)
.then((featureFlag) => {
if (featureFlag[nameOfTheFeature].enabled) {
resolve(true);
}
})
.catch(err => resolve(false));
});
}
在像这样的常规组件中调用它:
This is called in regular components like this:
render() {
return (<div>{await isFeatureEnabled('feature1') && <p>feature1 is enabled</p>}</div>)
};
它抛出了这个:
解析错误:无法在异步函数外使用关键字"await"
Parsing error: Can not use keyword 'await' outside an async function
如果我们添加async关键字,并带有正确的return语句:
If we add the async keyword, with a proper return statement:
async render() {
return (<div>{await isFeatureEnabled('feature1') && <p>feature1 is enabled</p>}</div>)
};
然后它抛出:
您的渲染方法应具有return语句
Your render method should have return statement
那么在React应用程序中使用此承诺函数的正确方法是什么?
So what is the correct way to use this promised function inside a react app?
推荐答案
我建议您不要在render
中使用await
关键字,而应使用componentDidMount
和constructor
并使用状态对象进行检查:
I would suggest you not to use await
keyword in render
instead use componentDidMount
and constructor
for this and use state object to check:
constructor(props){
super(props);
this.state = { isFeatEnabled: false };
}
componentDidMount(){
this.setState({isFeatEnabled:isFeatureEnabled('feature1')})
}
现在在渲染中:
render() {
return (<div>{this.state.isFeatEnabled && <p>feature1 is enabled</p>}</div>)
};
并从方法中删除async
.
这篇关于如何在React应用中使用承诺的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!