![](/img/trans.png)
[英]ReactJS, how to force synchronization when logging in a user and get info from the API?
[英]Get info from API request with parameters ReactJS
我试图根据我发送的信息从 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
它,你将它作为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 示例以供这里的人查看,那就太好了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.