【发布时间】:2018-11-11 03:44:35
【问题描述】:
我的 componentDidMount 生命周期函数中有一段代码执行以下操作
this.unsubscriber = auth().onAuthStateChanged((user: RNFirebase.User) => {
this.setState({ user });
});
onAuthStateChanged 返回一个 unsubscriber 函数,该函数需要在组件卸载时调用。问题是,如果我这样声明 unsubscriber 变量
constructor(props: {}) {
super(props);
this.unsubscriber: Function = null
}
typescript 抱怨说属性“unsubscriber”不存在(我也不能分配给函数,因为它是一个常量或只读属性)。我尝试做其他事情,比如将它作为这样的状态传递。
type AppState = {
user: RNFirebase.User | null;
unsubscriber: Function | null;
}
class App extends Component<{}, AppState> {
....
}
但这对我没有任何好处;当我尝试从onAuthStateChanged 分配返回值时遇到了同样的错误。如果我只是在没有打字稿的情况下做出反应,this.unsubscriber = null 会工作得很好,但我正在尝试同时使用两者。
我得到的最接近的是这个
type AppState = {
user: RNFirebase.User | null;
};
class App extends Component<{}, AppState> {
private unsubscriber: Function;
....
}
但是我得到的这个错误是它没有在那里或在构造函数中初始化,我不能给它分配 null。那我该怎么办?
这是我正在使用的全部代码。
import React, { Component } from 'react';
import { Text, View } from 'react-native';
import { auth, RNFirebase } from 'react-native-firebase';
import { Login } from './screens';
type AppState = {
user: RNFirebase.User | null;
};
class App extends Component<{}, AppState> {
private unsubscriber: Function; // This has to be initialized.
constructor(props: {}) {
super(props);
this.state = { user: null };
}
componentDidMount() {
this.unsubscriber = auth().onAuthStateChanged((user: RNFirebase.User) => {
this.setState({ user });
});
}
componentWillUnmount() {
if (this.unsubscriber) {
this.unsubscriber();
}
}
render() {
const { user } = this.state;
if (!user) {
return <Login />;
}
return (
<View>
<Text>Welcome to my awesome app {user.email}!</Text>
</View>
);
}
}
export default App;
【问题讨论】:
标签: typescript react-native react-native-firebase