如何在React中的表单提交上使用setState和fetch API?

我是React的新手,想玩fetchAPI。我想使用GoogleBooks API来显示与用户可以在输入字段中输入的查询字符串匹配的书籍列表。


我设法调用了Google API,并使用了setState,但无法保持状态。如果要在获取数据后呈现状态,则状态显示为未定义。


我有一种感觉,React首先呈现HTML,然后在进行API调用后设置状态。


如果您能看一下我的组件,我将不胜感激。


谢谢!


import React, {Component} from 'react'


class Search extends Component{

 constructor(props){

super(props)

this.state = {

  books: []


}

this.books = this.state.book

this.title = ''

this.handleChange = (e) => {

  this.title = e.target.value


}

this.handleSubmit = (e) => {

  let results = '';

  e.preventDefault();

  const apiKey = 'AIzaSyBuR7JI6Quo9aOc4_ij9gEqoqHtPl-t82g'

  fetch(`https://www.googleapis.com/books/v1/volumes?q=${this.title}&key=${apiKey}`)

  .then(response => response.json()).then(jsonData => {

    this.setState({

      books: jsonData

    })

    console.log(jsonData)

  })


}

}

 render(){


return(

  <div className="col-md-12">

    <form onSubmit={this.handleSubmit} className="form-group">

    <label>Enter title</label>

    <input onChange={this.handleChange} className="form-control" ref="title" type="text" placeholder="Enter title"></input>

    <button  type="submit" className="btn btn-primary">Submit</button>

    </form>

    <div>

      <li>this.state.books</li>

    </div>

  </div>


jeck猫
浏览 193回答 1
1回答

UYOU

你有:<li>this.state.books</li>这只是呈现一个字符串。相反,您可以map用来显示从响应中获得的书籍中的数据。这是一个工作示例:&nbsp;<div>&nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; this.state.books.items &&&nbsp; &nbsp; &nbsp; this.state.books.items.map(book => <li>{book.etag}</li>)&nbsp; &nbsp; }&nbsp;</div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript