使用参数ReactJS从API请求获取信息

时间:2019-07-17 01:16:00

标签: javascript json reactjs api fetch-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;

1 个答案:

答案 0 :(得分:1)

我认为问题在于您致电getStudents的方式。我认为您的API应该将请求有效载荷接受为application/json。但是通过stringify进行注册,您将其作为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示例以供工作,以便在这里的人可以看看,那就太好了。