【发布时间】:2020-01-17 01:03:40
【问题描述】:
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 })
})
}
有了这段代码,我有了想要呈现表格的数据,但我需要运行另一个 fetch 来获取其他信息,其中 id 来自第一个请求。
如何执行嵌套的获取请求?
非常感谢,
马修
【问题讨论】:
-
async/await是一个不错的选择,而不是写承诺。 Promise 会带你去回调地狱。
标签: javascript reactjs api fetch