javascript - 使用参数 ReactJS 从 API 请求中获取信息
问题描述
我正在尝试根据我发送的信息从 API 获取信息,但有两个问题:
我对发送到 API 的信息(年份和期限)进行了硬编码,因为它应该返回我试图存储的信息,但它不起作用
我正在尝试将它用作一个函数,然后填充表格,但由于它无法首先获取信息,所以它一直给我一个错误,所以我猜问题出在方式上我正在从 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;
解决方案
我认为问题在于你打电话的方式getStudents
。我认为您的 API 应该接受请求有效负载为application/json
. 但是通过stringify
ing 它,您将其发送为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 示例以供大家一起使用,那就太好了。
推荐阅读
- reactjs - Antd Forms,从自定义组件中获取值?
- python - 如何在 DEAP 遗传算法的每一代之后更新或调整评估函数
- matlab - matlab中csv文件的直方图
- java - 我可以使组件透明而不隐藏它吗?
- sql-server - 从存储过程插入期间“精度无效”?
- python - .insert() 函数不适用于我的输入框
- json - 使用 Laravel API 资源获取全日历中的事件
- python - 如何分离元素?
- php - 通过 swiftmail 发送电子邮件时重复
- chromecast - 使用 Chrome Sender API 获取 Google Cast 队列项目