我正在尝试从我的api中获取数据并将其设置为_data状态;但是,我总是将_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);
});
}
答案 0 :(得分:0)
你具体在哪里丢失"数据"值?你确定responseJson有"数据"它的价值在哪?
在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.
}