![](/img/trans.png)
[英]Can't build react-native app with xcode scheme and configuration
[英]React-Native app doesn't work if i use await
这是我第一次使用 react-native 开发 Android 应用程序。 当我从firestore
检索一些数据时,我正在尝试使用 async/await ,但是当我添加 await 这个词时,应用程序崩溃并且不再启动。 正如您在我的 package.json 文件中看到的那样,我使用react-native-firebase
库。 这是我的组件不起作用的部分:
componentDidMount() {
this.getAccountFromFirestore(this.props.user);
}
getAccountFromFirestore = async user => {
const accounts = await firebase
.firestore()
.collection('accounts')
.get();
this.setState({ loading: false });
};
这是我的 package.json,如果有用的话
{
"name": "myapp",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node node_modules/react-native/local-cli/cli.js start",
"test": "jest",
"ios": "react-native run-ios",
"android": "react-native run-android"
},
"dependencies": {
"native-base": "^2.8.1",
"react": "16.6.1",
"react-native": "0.57.6",
"react-native-firebase": "^5.1.1",
"react-native-navigation": "^1.1.493",
"react-native-vector-icons": "^6.1.0",
"react-redux": "^5.1.1",
"redux": "^4.0.1"
},
"devDependencies": {
"babel-jest": "23.6.0",
"jest": "23.6.0",
"metro-react-native-babel-preset": "0.49.2",
"react-test-renderer": "16.6.1"
},
"jest": {
"preset": "react-native"
}
}
您可以使用 Promise 实现,例如:
firebase
.firestore()
.collection('accounts')
.get()
.then(accounts => {
console.log ('Use accounts variable as per your requirement,'accounts)
})
.catch(error => {console.error(error)})
我不知道这是您的 React Native 还是您使用的是Node 6 。 但据我所知, async/await
仅在Node 8 或更高版本上受支持。 所以,你最好的选择仍然是使用Promises
来解决这个问题。 例如:
componentDidMount() {
this.getAccountFromFirestore(this.props.user);
}
getAccountFromFirestore = user => {
firebase
.firestore()
.collection('accounts')
.get()
.then(accounts => {
let data = accounts.docs.map(account => account.data());
console.log(data);
this.setState({ loading: false });
})
.catch(err => console.log(err));
};
同样在使用async/await
时,不要忘记try-catch
块:
componentDidMount() {
this.getAccountFromFirestore(this.props.user);
}
getAccountFromFirestore = async user => {
try {
const accounts = await firebase
.firestore()
.collection('accounts')
.get();
const data = accounts.docs.map(a => a.data());
console.log(data);
this.setState({ loading: false });
} catch (err) {
console.error(err);
}
};
选项 a) 继续使用 promises 选项 b) 迁移那个 RN,如果你可以使用 async/await,你的代码可能太旧了,无论如何都不能进入商店。 选项 c) Babel...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.