简体   繁体   English

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

[英]How to use setState with fetch API on form submit in React?

I'm new to React and wanted to play around with the fetchAPI. 我是React的新手,想玩fetchAPI。 I want to use the GoogleBooks API to display a list of books that matches a query string which the user can enter in an input field. 我想使用GoogleBooks API来显示与用户可以在输入字段中输入的查询字符串匹配的书籍列表。

I've managed to make the call to the Google API and have used setState but I can't get the state to stick. 我设法调用了Google API,并使用了setState,但无法保持状态。 If I want to render the state after fetching the data, the state appears as undefined. 如果要在获取数据后呈现状态,则该状态显示为未定义。

I have a feeling that React renders the HTML first and then sets the state after making the API call. 我有一种感觉,React首先呈现HTML,然后在进行API调用后设置状态。

I'd appreciate if you can have a look at my component. 如果您能看一下我的组件,我将不胜感激。

Thank you! 谢谢!

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>

You have: 你有:

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

This is just rendering a string. 这只是呈现一个字符串。

Instead, you can use map to show data from book you get from the response. 相反,您可以使用map显示从响应中获得的书籍中的数据。

Here's a working example: 这是一个工作示例:

 <div>
   {
      this.state.books.items &&
      this.state.books.items.map(book => <li>{book.etag}</li>)
    }
 </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM