2017-10-30 18 views
0

私のAPIからデータをフェッチして_data状態に設定しようとしています。しかし、私は常に定義されていない_data状態を取得します。まず、フェッチする前にasyncstorageからトークンを取得してから、データをフェッチから状態に保存する必要があります。誰かが私が何か間違っているかどうか確認してもらえますか?React Native - フェッチ時にデータが状態に設定されていません。

export default class Posts extends React.PureComponent { 
    constructor(props) { 
    super(props); 
    this.fetchData = this._fetchData.bind(this); 
    this.state = { 
     isLoading: true, 
     isLoadingMore: false, 
     _data: null, 
     accessToken: "", 
    }; 
    } 

async componentWillMount() { 
try { 
     let accessToken = await AsyncStorage.getItem(ACCESS_TOKEN).then(JSON.parse); 
     if(!accessToken) { 
      this.redirect('login'); 
     } else { 
     this.setState({accessToken: accessToken}) 
    } 
} catch(error) { 
    console.log("Something went wrong"); 
    this.redirect('login'); 
} 

this.fetchData(responseJson => { 
    const data = responseJson.data; 
    this.setState({ 
    isLoading: false, 
    _data: data, 
    }); 
}); 
}  

    _fetchData(callback) { 
    fetch(`https://mywebsite.com/posts`, 
     { 
     method: 'GET', 
     headers: { 
      'Accept': 'application/json', 
      'Content-Type': 'application/json', 
      'Authorization': "Bearer " + this.state.accessToken.token, 
     } 
    }) 
     .then(response => response.json()) 
     .then(callback) 
     .catch(error => { 
     console.error(error); 
     }); 
    } 

答えて

0

「データ」の値は特に失われていますか? responseJsonに "data"という値が入っていますか?

の範囲を失う可能性があります。これは、のbind()呼び出し後です。試してみてください:

constructor(props) { 
    var self = this; 
    super(props); 
    this.fetchData = this._fetchData.bind(this); 
    this.state = { 
     isLoading: true, 
     isLoadingMore: false, 
     _data: null, 
    accessToken: "", 
    }; 

    // self.data here should be there if this.data is not. 
} 
+0

これはうまくいきました! – nocarrier

関連する問題