反应本机保存响应

React Native Save Response

我正在学习使用 React Native 编写代码并使用它与 GitHub API 进行交互。 我使用下面的代码来获取我所有通知的数据。

首先,加载 Asyncstorage 用户名和密码后,它不会发送提取调用。它正在返回一条需要身份验证的消息。我在使用 Asyncstorage 时做错了什么吗?当我在不同的页面中使用它时它工作得很好,除了它没有像在 componentDidMount 上那样获取,而是仅在按下按钮期间获取。

我通过硬编码我的用户名和密码暂时绕过了身份验证,这让我想到了第二个问题。我无法使用我保存到状态的通知数据。我做错了什么以及如何正确使用保存它。

最后,如何使用带有平面列表的已保存响应来显示所有通知标题?我无法保存 array/dictionary 以传递给 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,
    })));
}

不需要将mainusernamemainpassword存入状态,可以利用closure属性。考虑以下代码段。

let base64 = require('base-64');
AsyncStorage.getItem('mainusername').then(username => {
  AsyncStorage.getItem('mainpassword').then(password => {
    fetch("https://api.github.com/notifications",{
      method: "GET",
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Basic ' + base64.encode(username + ':' + password),
      },
    })
    .then((response) => response.json())
    .then(res => {
      this.setState({
        notidata: res
      });
    });
  });
});

使用上面的代码我能够获得所有通知。

现在,来到你的最后一个问题,如何显示 title,答案是你需要根据你的要求处理 response。要在 FlatList 中显示此内容,您需要更改上面代码段

中的最后一个 .then
.then(res => {
  let notis = [];
  Object.keys(res).forEach((val, index) => {
    notis.push({ data: res[val].subject.title, key: `litItem${index}` });
  });
  this.setState({
   notidata: notis
  });
});

现在将 FlatListdata 属性 设置为 this.state.notidata 并在 renderItem 函数中,访问 title 作为 item.data.

希望这会有所帮助!