首页 > 解决方案 > 使用参数 ReactJS 从 API 请求中获取信息

问题描述

我正在尝试根据我发送的信息从 API 获取信息,但有两个问题:

  1. 我对发送到 API 的信息(年份和期限)进行了硬编码,因为它应该返回我试图存储的信息,但它不起作用

  2. 我正在尝试将它用作一个函数,然后填充表格,但由于它无法首先获取信息,所以它一直给我一个错误,所以我猜问题出在方式上我正在从 API 请求信息(我是整个 React/JavaScript 的新手)

这就是我的代码的样子

class Stu extends Component {
  constructor(props) {
    super(props);

    this.state = {
      students: [],
    }
    this.fetch = this.fetch.bind(this)
    this.getStudents = this.getStudents.bind(this)
  }

  getStudents(year, term) {
    return this.fetch(`http://10.123.456.321/Stu/`, {
        method: 'POST',
        body: JSON.stringify({
            year,
            term
        })
    }).then(data => {
      this.setState({
        students: data.results.map(item => ({
          firstName: item.firstName,
          lastName: item.lastName,
          ID: item.ID,
          term: item.term,
          year: item.year,
        }))

      })
      console.log(this.state);
    })
  }

  fetch(url, options) {
    // performs api calls sending the required authentication headers
    const headers = {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    }

    return fetch(url, {
        headers,
        ...options
    })
        .then(response => response.json())
  }

  renderTableData() {
    return this.state.projects.map((student, index) => {
       const { firstName, lastName, ID, term, year } = student
       return (
          <tr>
             <td>{firstName}</td>
             <td>{lastName}</td>
             <td>{ID}</td>
             <td>{term}</td>
             <td>{year}</td>
          </tr>
       )
    })
  }
// 

  render() {
    return (
      <Container>
        {this.getStudents("2019", "summer")} // this is supposed to be called from a button click, but I tried hardcoding those values and it doesn't call the API properly, both values are strings
        <Form>
          <div>
          <table id='students'>
               <tbody>
               <tr>
                <th>First Name</th>
                <th>Last Name</th>
                <th>ID</th>
                <th>Term</th>
                <th>Year</th>
               </tr>
               {this.renderTableData()}
               </tbody>
            </table>
          </div>
        </Form> 
      </Container>
    );
  }
}

export default Stu;

标签: javascriptjsonreactjsapifetch-api

解决方案


我认为问题在于你打电话的方式getStudents。我认为您的 API 应该接受请求有效负载为application/json. 但是通过stringifying 它,您将其发送为string. 因此问题。

摆脱JSON.stringify呼叫并尝试它是否有效:

getStudents(year, term) {
  return this.fetch(`http://10.123.456.321/Stu/`, {
    method: 'POST',
    body: {
      year,
      term
    }
  }).then(data => {
    this.setState({
      students: data.results.map(item => ({
        firstName: item.firstName,
        lastName: item.lastName,
        ID: item.ID,
        term: item.term,
        year: item.year,
      }))

    })
    console.log(this.state);
  })
}

也可能有其他问题。如果您可以共享一个最小的 CodeSandbox 示例以供大家一起使用,那就太好了。


推荐阅读