Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
265 views
in Technique[技术] by (71.8m points)

React Native AsyncStorage fetches data after rendering

I am using AsyncStorage in ComponentWillMount to get locally stored accessToken, but it is returning the promise after render() function has run. How can I make render() wait until promise is completed? Thank you.

question from:https://stackoverflow.com/questions/33553112/react-native-asyncstorage-fetches-data-after-rendering

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can't make a component wait to render, as far as I know. What I've done in the app I'm working on is to add a loading screen until that promise from AsyncStorage resolves. See the examples below:

//
// With class component syntax
//

import React from 'react';
import {
  AsyncStorage,
  View,
  Text
} from 'react-native';

class Screen extends React.Component {

  state = {
    isLoading: true
  };

  componentDidMount() {
    AsyncStorage.getItem('accessToken').then((token) => {
      this.setState({
        isLoading: false
      });
    });
  },

  render() {
    if (this.state.isLoading) {
      return <View><Text>Loading...</Text></View>;
    }
    // this is the content you want to show after the promise has resolved
    return <View/>;
  }

}
//
// With function component syntax and hooks (preferred)
//

import React, { useEffect } from 'react';
import {
  AsyncStorage,
  View,
  Text
} from 'react-native';

const Screen () => {

  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    AsyncStorage.getItem('accessToken').then((token) => {
      setIsLoading(false);
    });
  }, [])

  if (isLoading) {
    return <View><Text>Loading...</Text></View>;
  }
  // this is the content you want to show after the promise has resolved
  return <View/>;

}

Setting the isLoading property in state will cause a re-render and then you can show the content that relies on the accessToken.

On a side note, I've written a little library called react-native-simple-store that simplifies managing data in AsyncStorage. Hope you find it useful.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...