【发布时间】:2019-02-04 14:23:53
【问题描述】:
我试图通过从我的数据库中获取一个值然后使用它来设置用户的状态。由于某种原因,状态不会自行更新,我尝试过等待和异步。如果此选项不可靠以使其成为一个值,还有哪些其他选项。
我确实收到以下错误:Warning: Can't call setState (or forceUpdate) on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.
- node_modules/fbjs/lib/warning.js:33:20 in printWarning
- node_modules/fbjs/lib/warning.js:57:25 in warning
- node_modules/react-native/Libraries/Renderer/ReactNativeRenderer-dev.js:12196:6 in warnAboutUpdateOnUnmounted
- node_modules/react-native/Libraries/Renderer/ReactNativeRenderer-dev.js:13273:41 in scheduleWorkImpl
- node_modules/react-native/Libraries/Renderer/ReactNativeRenderer-dev.js:6224:19 in enqueueSetState
- node_modules/react/cjs/react.development.js:242:31 in setState
* null:null in componentWillMount$
- node_modules/regenerator-runtime/runtime.js:62:44 in tryCatch
- node_modules/regenerator-runtime/runtime.js:296:30 in invoke
- ... 13 more stack frames from framework internals
constructor() {
super();
this.state = {
userPhoneNumber: "",
};
}
async componentWillMount() {
await firebase.database().ref('/Users/' + firebase.auth().currentUser.uid).on('value', async snap => {
if (snap) {
await this._setPhone(snap.val())
} else {
this.props.navigation.navigate('Phone')
}
});
console.log(this.state.userPhoneNumber);
}
_setPhone = (snap) => {
const val = parseInt(snap, 10);
this.setState({
userPhoneNumber: val
})
};
【问题讨论】:
-
这很奇怪。它应该工作。不过这里不需要
await:await this._setPhone(snap.val()) -
请输入有效的JS类语法,为什么用
await调用this._setPhone()? -
添加了 await 作为使这项工作都不起作用的另一种尝试
-
您在导航离开后在某处设置状态,请确保您不这样做。您可能忽略了这个组件的关键部分,很难说在哪里。
-
您在此代码中不需要任何
async和await,因为我看到您使用的是回调方法,您应该使用componentDidMount而不是componentWillMount,然后再一次,请提供有效的类语法,以确保您的问题与其他问题无关
标签: javascript firebase react-native firebase-realtime-database