代码之家  ›  专栏  ›  技术社区  ›  sortinousn

异步存储。使用fetch-React Native时返回未定义的getItem

  •  3
  • sortinousn  · 技术社区  · 7 年前

    Cannot read property 'getItem' of undefined

    签名。js组件

    //Function is bound
    async signIn() {
    const data = JSON.stringify({username: this.state.username, password: this.state.password})
    
      await fetch(`https://somesecretdomain.com:8443/users/login`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      body: data
    }).then((response) => response.json()).then(async(responseJson) => { 
      AsyncStorage.setItem('jwt', responseJson.id_token);
    
      const resetAction = NavigationActions.reset({
        index: 0,
        actions: [NavigationActions.navigate({routeName: 'Profile'})]
      });
      this
        .props
        .navigation
        .dispatch(resetAction);
    }).catch((error) => {
      console.warn(error);
    })
    };
    

    轮廓js组件

    async fetchData() {
    AsyncStorage
      .getItem('jwt')
      .then((value) => {
        this.setState({"TOKEN": value});
      })
      .done();
    
    console.log(this.state.TOKEN)
    const response = await 
    fetch(`https://somesecretdomain.com:8443/users/getUsers`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'token': this.state.TOKEN
      }
    })
    const json = await response.json()
    

    }

    我更改了个人资料。js组件到下面,仍然得到相同的错误。

    import React, {AsyncStorage, localStorage} from 'react';
    import {
    Text,
    View,
    Image,
    TouchableHighlight,
    WebView,
    TextInput,
    KeyboardAvoidingView,
    ScrollView
    } from 'react-native';
    
     async fetchData() {
     const TOKEN = await AsyncStorage.getItem('jwt');
     const response = await 
     fetch(`https://somedomain.com:8443/users/getUsers`, {
     method: 'GET',
     headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
    'token' : TOKEN
    },
    });
    const result = await response.json();
      this.setState({data: result})
    }
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   yedidyak    7 年前

    试试这个:

    async signIn() {
        const data = JSON.stringify({username: this.state.username, password: this.state.password})
    
      const response = await fetch(`https://somesecretdomain.com:8443/users/login`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      body: data
      });
      const result = await response.json();
      await AsyncStorage.setItem('jwt', result.id_token);
    
      const resetAction = NavigationActions.reset({
        index: 0,
        actions: [NavigationActions.navigate({routeName: 'Profile'})]
      });
      this
        .props
        .navigation
        .dispatch(resetAction);
    });
    };