从 API 请求中获取答案作为数组

Get answers from API request as array

我正在尝试发出 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'));

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

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)})
  });
}

问题是:(我在日志中看到这个错误)

Uncaught (in promise) Error: Objects are not valid as a React child (found: object with keys {q, from, to, params, more, count, hits}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of [MyComponent]...

所以实际上,第二个回调中的resp是一个对象,无法渲染,所以你可以将其转换为字符串,看看你的API是否有效,或者循环对象来渲染它根据您的需要适当!

随时 post 在您的控制台中发现一些新错误,以便我们找到呈现数据的好方法,谢谢