AsyncStorage React Native Session

时间:2017-12-15 05:03:13

标签: react-native asyncstorage

当我运行我的应用程序时,如果我在AsyncStorage中有会话数据,我加载它,但它在组件安装后加载并作为未定义发送到mainContainer,我需要先加载数据然后将其发送到MainContainer < / p>

export default class AppContainer extends Component<{}> {
    constructor(props) {
        super(props);

        this.state = {
            data: this.props.data,
            authtoken: this.props.authtoken,
            sucursal: this.props.sucursal
        };
    }


    componentWillMount() {
        if(AsyncStorage.getItem('authtoken') !== null){
        this.getDataFromStorage();
        }
    }

    async getDataFromStorage() {
        AsyncStorage.getItem('authtoken').then((token) => {
            this.setState({ authtoken: token });
            console.log(this.state.authtoken);
        });
        AsyncStorage.getItem('data').then((dataStorage) => {
            this.setState({ data: JSON.parse(dataStorage) });
            console.log(this.state.data);
        });
    }

    componentDidMount() {
        console.log(this.state.data);
        console.log(this.state.authtoken);

    }




    render(props) {
        return (
            <View style={styles.bigContainer}>
                <Header/>
                <MainContainer data={this.state.data} authtoken={this.state.authtoken} sucursal={this.state.sucursal}/>
            </View>
        );
    }

}

1 个答案:

答案 0 :(得分:0)

将加载指示器引入组件树。检查this.state.data的值。只有在渲染数据后才停止指示。

render(props) {
    return (
        <View style={styles.bigContainer}>
            <ActivityIndicator animating={!this.state.data} size="large" color="#0000ff" />
            <Header/>
            <MainContainer data={this.state.data} authtoken={this.state.authtoken} sucursal={this.state.sucursal}/>
        </View>
    );
}

您可能需要更改样式。