如何在生命周期功能中访问上下文?

时间:2019-02-01 06:14:28

标签: react-native

我看了以下question,但仍然无法在生命周期方法中访问上下文。它总是返回一个空对象。但是,如果我尝试使用<UserContext.Consumer>语法访问上下文,则可以访问该上下文。如何在生命周期方法中访问上下文?

App.tsx

export const UserContext = createContext({});

interface IProps { }
interface IState {
  user: User
}

export default class App extends Component<IProps, IState> {
  public readonly state: IState = {
    user: {}
  }
  private authenticationService: IAuthenticationService;

  constructor(props: IProps) {
    super(props);
    this.authenticationService = new FirebaseAuthenticationService();
  }

  public componentDidMount() {
    this.setState({ user: this.authenticationService.GetCurrentUser() });
  }

  public render() {
    return (
      <UserContext.Provider value={this.state.user}>
        <AppContainer />
      </UserContext.Provider>
    );
  }
}

AuthenticationScreen.tsx

interface IState {
  animating: boolean
}

class AuthenticationScreen extends Component<NavigationScreenProps, IState> {
  public static contextType = UserContext;
  public readonly state: IState = {
    animating: false
  }

  public componentDidMount() {
    console.warn(this.context);
  }

  public render() {
    return (
      <View style={Styles.container}>
        {this.state.animating && <ActivityLoaderContainer animating={this.state.animating} />}
      </View>
    );
  }
}
export default AuthenticationScreen;

根据文档,我已经在子组件中正确设置了上下文类型。

0 个答案:

没有答案