【问题标题】:How do I solve this property declaration error that typescript keeps complaining to me?如何解决打字稿一直向我抱怨的这个属性声明错误?
【发布时间】: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


    【解决方案1】:

    我建议您将 unsubscriber 声明保留为类成员,但将其设为可选 (optional class properties)。此外,Function 类型通常根本没有用(只需看看它定义的接口是什么),如果它的返回值将被忽略,你最好将其类型定义为 () =&gt; void(参见callback types)。所以,试试这样的:

    private unsubscriber?: () => void;
    

    【讨论】:

      【解决方案2】:

      你只需要初始化unsubscriber属性:

      private unsubscriber: (() => void) | null = null;
      

      【讨论】:

        猜你喜欢
        • 2022-06-13
        • 1970-01-01
        • 2018-10-14
        • 2020-03-15
        • 2018-03-16
        • 2020-09-06
        • 1970-01-01
        • 2020-01-06
        • 1970-01-01
        相关资源
        最近更新 更多