React API 返回空

IT技术 reactjs
2021-05-11 07:10:06

react相当新,但我有以下 API 数据我想创建为列表或其他任何内容:

https://jsonblob.com/53c7f296-d79d-11e8-839a-a312b719c60a

我的react组件如下所示:

class Contacts extends Component {
  constructor(props) {
   super(props)
   this.state = {
     contacts:[]
   }
 }

 componentDidMount() {
   fetch('https://api.billysbilling.com/v2/contacts?organizationId=kZeGqbBRSXyeeDoWNkF3jQ',{
     headers: {
         'X-Access-Token': API_KEY,
         'Content-Type': 'application/json'
     },
   })
    .then(response => {
      return response.json();
    })
    .then(response => console.log(response))
    .then(d => {
      this.setState({ contacts: d });
      console.log("state", this.state.contacts)
    })
  }
  render() {
  return (
    <div>
      {
        this.state.contacts.map(((contact, index) =>
          <th key={`${contact.contact}${index}`}>
            <div>
              <div>
                {contact.contact}

              </div>
            </div>
          </th>
        ))
      }
    </div>
  );
}

但是,它似乎什么也没有返回。console.log 实际上显示了数据,所以我很困惑。如果你们中的一些人可以提供帮助,那就太棒了。

状态也只是在 chrome 的react工具中返回一个空数组。

1个回答

当您编写 时then(response => console.log(response)),您不会返回任何内容,因此dundefined在以下函数中返回then

你可以这样写:

fetch('https://api.billysbilling.com/v2/contacts?organizationId=kZeGqbBRSXyeeDoWNkF3jQ',{
  headers: {
    'X-Access-Token': API_KEY,
    'Content-Type': 'application/json'
  },
})
.then(response => {
  return response.json();
})
.then(d => {
  console.log(d);
  this.setState({ contacts: d.contacts });
});