Reactjs 以数组形式从API请求获取答案

Reactjs 以数组形式从API请求获取答案,reactjs,fetch,Reactjs,Fetch,我正在尝试发出一个API请求并显示它们,我认为我必须将它们呈现为数组,但在这方面有问题。这是我的密码 class RecipesList extends React.Component { constructor(props) { super(props); this.state = { searchResult: '' }; } componentDidMount() { fetch('http

我正在尝试发出一个API请求并显示它们,我认为我必须将它们呈现为数组,但在这方面有问题。这是我的密码

      class RecipesList extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        searchResult: ''
      };
    }
    componentDidMount() {
      fetch('https://api.edamam.com/search?q=chicken&app_id=ec279fce&app_key=51017bcd32e69bcb0cc8b5f99e8783ca')
      .then(resp => resp.json())
      .then(resp => this.setState({searchResult: resp})
      );
    }
    render() {
      return <div>{this.state.searchResult}</div>  //???
    }
  }

  class App extends React.Component {
    render() {
      return <RecipesList/>;
    }
  }

  ReactDOM.render(
    <App/>, document.querySelector('#app'));
类配方列表扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
搜索结果:“”
};
}
componentDidMount(){
取('https://api.edamam.com/search?q=chicken&app_id=ec279fce&app_key=51017bcd32e69bcb0cc8b5f99e8783ca')
.then(resp=>resp.json())
.then(resp=>this.setState({searchResult:resp})
);
}
render(){
返回{this.state.searchResult}/???
}
}
类应用程序扩展了React.Component{
render(){
返回;
}
}
ReactDOM.render(
,document.querySelector(“#app”);

如果您只想查看数据,只需执行以下操作:

componentDidMount() {
  fetch('https://api.edamam.com/search?q=chicken&app_id=ec279fce&app_key=51017bcd32e69bcb0cc8b5f99e8783ca')
  .then(resp => resp.json())
  .then(resp => this.setState({searchResult: JSON.stringify(resp)})
  );
}
您还可以记录响应对象,如:

componentDidMount() {
  fetch('https://api.edamam.com/search?q=chicken&app_id=ec279fce&app_key=51017bcd32e69bcb0cc8b5f99e8783ca')
  .then(resp => resp.json())
  .then((resp) => {
    console.log(resp);
    this.setState({searchResult: JSON.stringify(resp)})
  });
}
问题是:(我在日志中看到了这个错误)

未捕获(承诺中)错误:对象作为子对象无效 (找到:具有键{q、from、to、params、more、count、hits}的对象)。如果 要呈现子对象集合,请改用数组或 使用React附加组件中的createFragment(对象)包装对象。 检查[MyComponent]的呈现方法

因此,实际上,第二次回调中的resp是一个无法渲染的对象,因此您可以将其转换为字符串以查看API是否工作,或者根据需要循环对象以正确渲染它


请随意在控制台中发布一些新错误,这样我们就可以找到一种很好的方法来渲染数据,谢谢

您能在api响应中显示
searchResult
数据吗?您可以在这里检查它,它是一个包含许多数组的对象,您想在这里渲染什么?