React Native:AsyncStorage返回值[object Object](iOS)

时间:2018-05-28 00:38:01

标签: reactjs react-native react-native-android react-native-ios react-native-router-flux

我尝试登录我的API,保存令牌并转到下一页。因此,我解决了使用AsyncStorage保存令牌的问题,然后在标头中发送令牌以获取数据。请参阅Login.js类:

  

Login.js

export default class Login extends React.Component {
  constructor (props) {
    super (props);
    this.state = { tokenValue: '' }
  }  
  updateTokenValue= (tv) => { this.setState({tokenValue : tv}); }

  async saveToken() {
    try { await AsyncStorage.setItem('tokenvalue', this.updateTokenValue(this.state.tokenValue)); } 
    catch (error) { console.error('[APIREQUEST] AsyncStorage error: ' + error.message); }
  }

  onLogin() {
  axios.post('http://my-api-url/login', {
        'credential': this.state.txtInputUser,
        'password': this.state.txtInputPassword
    })
    .then((response) => {        
      if(response.status != 200){
        Alert.alert('ERROR’, ‘USER or PASSWORD INVALIDATE’);
      } else {
        console.log("Login success”);
        console.log(response.data.token+" | Status: "+response.status); 
        saveToken(response.data.token); 
               //   open the next screen
        Actions.searchproduct ({
          userID: 0,
        });  
      }
    })
    .catch(function (error) {
        console.log('Error: '+error)
        return;
    });
  }

  render() {
    return (
      <View style={styles.container}>      
              <TextInput style={styles.inputFields} value={'mobi-dev@blendmobi.com'} onChangeText={txtInputUser => this.setState({txtInputUser})} placeholder={'Usuário'} placeholderTextColor={'#9E9E9E'}/>
              <TextInput style={styles.inputFields} value={'Blend@03'} onChangeText={txtInputPassword => this.setState({txtInputPassword})} placeholder={'Senha'} placeholderTextColor={'#9E9E9E'}/>           
              <MyButton w="100%" h={55} mt={5} as="stretch" so={0.1} ai="center" bg="#212121" tc="#F5F5F5" fs={22} t="LOGIN" onPress={() => this.onLogin()}/>
            </View>
      </View>
    );
  }
}

和我的SearchProduct类:

  

SearchProduct.js

//  imports

export default class SearchProduct extends React.Component {
  constructor(props) {
    super(props);
    this.state = { tokenValue: '', };
  }

  getTokenValue= (tv) => { this.setState({tokenValue : tv}); }

  componentDidMount() {
    var valueToken = '';
    try{
      const token = AsyncStorage.getItem('tokenvalue');
      if (token != null) {
        valueToken = token;
        console.log('[SEARCHPRODUCT] Token saved: '+valueToken);
      } else {
        console.log('[SEARCHPRODUCT] Token empty’);
      }
    } catch(error) {
      console.log('[SEARCHPRODUCT] ERROR TO GET THE TOKEN: '+error);
    }

    axios.get('http://my-api-url/listdata’, {
      headers: {
        Authorization: 'Bearer '.concat(valueToken)
      },
    })
    .then((response) => {
      console.log(response);
    })
    .catch((e) => {
        console.log('ERROR TO SYNC: '+e)
    });
  }
//  …
}

在浏览器的控制台中,返回给我的数据是:[object Object] OBS:它是我回复给我的JSON模型:

{
    "id": "5b048159952a12c06c1d4305",
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoiYmFja29mZmljZSIsImRlbGV0ZWQiOmZhbHNlLCJ1cGRhdGVkQXQiOiIyMDE4LTA1LTI4VDAwOjM4OjM2LjEzN1oiLCJfaWQiOiI1YjA0ODE1OTk1MmExMmMwNmMxZDQzMDUiLCJuYW1lIjoiTW9iaSIsInN1cm5hbWUiOiJEZXYiLCJlbWFpbCI6Im1vYmktZGV2QGJsZW5kbW9iaS5jb20iLCJfc3RvcmVJZCI6IjVhZjQ2MDRlMzMxZTBhMjRjNDM3YWE0ZSIsImlhdCI6MTUyNzQ2NzkxNn0.Yb-ImCWAzv88wtQE65p1Ejv7q8n4rmGsmIsj_DCiSfI"
}

1 个答案:

答案 0 :(得分:0)

您可以更改saveToken函数,如下所示

async saveToken() {
    try { 
       await this.updateTokenValue(this.state.tokenValue);
       await AsyncStorage.setItem('tokenvalue', this.state.tokenValue); 
        } 
     catch (error)
       { 
        console.error('[APIREQUEST] AsyncStorage error: ' + error.message); 
       }
     }