React Native - async / await不起作用

时间:2017-06-23 10:16:12

标签: javascript react-native

是否可以在类之外使用async / await? 例如,我使用AsyncStorage存储访问令牌,并希望在初始化StackNavigator之前获取此令牌。

container.js

import React from 'react';
import { StackNavigator } from 'react-navigation';
import PairingView from '../components/PairingView';
import MainView from '../components/MainView';
import { getTokenFromStorageAsync } from '../helpers/asyncStorageHelper';

const accessToken = getTokenFromStorageAsync().done();
console.log(accessToken);   <---------- undefined

const AppNavigator = StackNavigator({
  PairingRoute: {
    screen: PairingView
  },
  MainRoute: {
    screen: MainView
  }
}, {
  initialRouteName: (accessToken == null) ? 'PairingRoute' : 'MainRoute',
  initialRouteParams: {
    token: accessToken
  }
});

const App = () => (
  <AppNavigator />
);

export default App;

asyncStorageHelper.js

import { AsyncStorage } from 'react-native';

export const getTokenFromStorageAsync = async () => {
  try {
    const value = await AsyncStorage.getItem('@nfs:token');
    console.log(value);   <---------- access token
    if (value != null)
      return value;
  } catch (err) {
    console.error(err);
  }
  return undefined;
};

2 个答案:

答案 0 :(得分:1)

解决了这个问题。

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      accessToken: 'fetching'
    };

    this._loadAccessToken();
  }

  _loadAccessToken = async () => {
    const token = await getTokenFromStorageAsync();
    this.setState({ accessToken: token });
  }

  render() {
    if (this.state.accessToken === 'fetching')
      return null;

    const AppNavigator = StackNavigator({
      PairingRoute: {
        screen: PairingView
      },
      MainRoute: {
        screen: MainView
      }
    }, {
      initialRouteName: (this.state.accessToken == null) ? 'PairingRoute' : 'MainRoute',
      initialRouteParams: {
        token: this.state.accessToken
      }
    });

    return <AppNavigator />;
  }
}

export default App;

答案 1 :(得分:0)

getTokenFromStorageAsync().then(accessToken => {
    console.log(accessToken);
    // ...
});

// ...
export default (async () => {

    const accessToken = await getTokenFromStorageAsync();
    console.log(accessToken);

    const AppNavigator = StackNavigator({
      PairingRoute: {
        screen: PairingView
      },
      MainRoute: {
        screen: MainView
      }
    }, {
      initialRouteName: (accessToken == null) ? 'PairingRoute' : 'MainRoute',
      initialRouteParams: {
        token: accessToken
      }
    });

    const App = () => (
      <AppNavigator />
    );

    return App;

})()

正如您所看到的,您必须导出使用您的应用程序解决的承诺,而不是直接导出您的应用程序。

编辑:

import { AppRegistry } from 'react-native';
import App from './app/container';
(async () => {
    let ResolvedApp = await App()
    AppRegistry.registerComponent('someappname', () => ResolvedApp);
    // ...
})()