Javascript React Native-提取时数据未设置为状态

Javascript React Native-提取时数据未设置为状态,javascript,reactjs,react-native,fetch,Javascript,Reactjs,React Native,Fetch,我试图从我的api获取数据并将其设置为_data状态;但是,我总是将_数据状态设置为未定义。首先,我在提取之前从异步存储中提取一个令牌,然后我想将提取的数据保存到状态。有人能检查一下我是否做错了什么吗 export default class Posts extends React.PureComponent { constructor(props) { super(props); this.fetchData = this._fetchData.bind(this);

我试图从我的api获取数据并将其设置为_data状态;但是,我总是将_数据状态设置为未定义。首先,我在提取之前从异步存储中提取一个令牌,然后我想将提取的数据保存到状态。有人能检查一下我是否做错了什么吗

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);
      });
  }

具体在哪里丢失“数据”值?您确定responseJson中包含“数据”值吗

在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.
 }