React Native - 数据在获取时未设置状态

React Native - data is not set in state when fetching

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

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

您具体在哪里丢失了 "data" 值?您确定 responseJson 中有 "data" 值吗?

在调用 bind() 之后,您可能会失去 this 的作用域;试试这个:

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