【发布时间】:2018-04-04 14:20:32
【问题描述】:
我正在学习使用 react native 编写代码并使用它与 GitHub API 进行交互。 我使用下面的代码来获取我所有通知的数据。
首先,它在加载 Asyncstorage 用户名和密码后不会发送 fetch 调用。它正在返回需要身份验证的消息。我在 Asyncstorage 上做错了吗?当我在不同的页面中使用它时它工作得很好,除了没有像在 componentDidMount 上那样获取,而是仅在按下按钮期间。
我通过硬编码我的用户名和密码暂时绕过了身份验证,这将我带到了第二个问题。我无法使用我保存的通知数据。我在做什么错以及如何正确使用保存它。
最后,如何使用已保存的响应和 Flatlist 来显示所有通知标题?我无法保存数组/字典以传递给 Flatlist,所以我不知道该怎么做。我可以像下面这样传入保存的数组吗:
<FlatList
data={this.state.notidata}
renderItem={this._renderItem}
/>
_renderItem = ({item}) => {
return (
<TouchableHighlight
underlayColor='#dddddd'>
<View>
<Text>{item.id}</Text>
</View>
</TouchableHighlight>
);
};
实际代码是
constructor() {
super();
this.state = {
notidata: [],
mainusername: '',
mainpassword: '',
showdone: '',
};
}
componentDidMount () {
let base64 = require('base-64');
AsyncStorage.getItem("mainusername").then((value) => {
this.setState({mainusername: value});
})
.then(
AsyncStorage.getItem("mainpassword").then((value) => {
this.setState({mainpassword: value});
}).done())
.then(
fetch("https://api.github.com/notifications",{
method: "GET",
headers: {
'Content-Type': 'application/json',
'Authorization': 'Basic ' + base64.encode(this.state.mainusername + ':' + this.state.mainpassword),
},
})
.then((response) => this.setState({
notidata: response,
})));
}
【问题讨论】:
标签: react-native response github-api react-native-flatlist asyncstorage