React 新手,我目前正在尝试使用来自 API 的数据创建数据表。 我想要第一次获取,然后使用第一个 (id) 的响应运行另一个以完成我的表。
这是我的代码:
class HomePage extends React.Component {
constructor(props) {
super(props);
this.state = {
user: {},
data: []
};
}
componentDidMount() {
this.setState({
user: JSON.parse(localStorage.getItem('user'))
}, function () {
this.loadAllObjectsInfo()
});
}
// Fetch all object info in order to fill the table
loadAllObjectsInfo() {
const requestOptions = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'bbuser': this.state.user.userId,
'bbtoken': this.state.user.secret
},
};
fetch('https://xxxxx/api/objects', requestOptions)
.then(response => response.json())
.then((data) => {
this.setState({ data: data })
})
}
使用这段代码,我有了要呈现我的表格的数据,但我需要运行另一次提取以获取其他信息以及来自第一个请求的 ID。
我怎样才能执行嵌套的提取请求?
非常感谢,
马修
最佳答案
您可以使用 async/await
轻松管理它:
async loadAllObjectsInfo() {
const requestOptions = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'bbuser': this.state.user.user
'bbtoken': this.state.user.secret
},
};
let response = await fetch('https://xxxxx/api/objects', requestOptions);
let data = await response.json();
// here is another fetch - change to fit your request parameters (this is just example)
let info = await fetch('https://xxxxx/api/objects/' + data.id);
this.setState({ data });
}
您可以阅读更多关于 async function 的信息.
关于javascript - React 中嵌套获取请求的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57952669/