Javascript React中的嵌套获取请求存在问题
新的反应,我目前正试图创建一个数据表与数据从一个API。 我希望先进行一次获取,然后运行另一次获取,并从第一个(id)返回响应,以完成我的表 这是我的密码:Javascript React中的嵌套获取请求存在问题,javascript,reactjs,api,fetch,Javascript,Reactjs,Api,Fetch,新的反应,我目前正试图创建一个数据表与数据从一个API。 我希望先进行一次获取,然后运行另一次获取,并从第一个(id)返回响应,以完成我的表 这是我的密码: class HomePage extends React.Component { constructor(props) { super(props); this.state = { user: {}, data: [] }; }
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的其他信息
如何执行嵌套的获取请求
非常感谢
Matthieu您可以编写如下代码
fetch('https://xxxxx/api/objects', requestOptions)
.then(response => response.json())
.then((res1) => {
fetch('https://xxxxx/api/objects', requestOptions)
.then(response => response.json())
.then((res2) => {
this.setState({ data: res2 });
});
});
希望这对你有用 您可以使用
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 });
}
您可以阅读有关的更多信息。@JourdanM,您应该从一个
然后处理程序返回一个新的获取
请求。我给你写了一个简单的片段。没有数据验证程序和微调器。这是一个简单的展示。=)
fetch
请求返回一个承诺,您可以通过从然后处理程序返回承诺来链接承诺。这是一篇关于它的好文章,它有很好的例子:
函数fetchUser(用户){
回传(`https://api.github.com/users/${user.login}`)
}
类用户扩展了React.Component{
状态={
用户:空
}
组件安装(){
取回(“https://api.github.com/users")
.then(response=>response.json())
。然后(用户=>fetchUser(用户[0]))
.then(response=>response.json())
。然后(用户=>{
this.setState({user})
})
}
渲染(){
返回(
{JSON.stringify(this.state.user,null,2)}
)
}
}
ReactDOM.render(,document.querySelector(“#root”)代码>
您也可以像下面这样使用axios
async/await
是一个不错的选择,而不是写承诺。承诺会让你下地狱。
axios.post(url, data, header).then(res => {
if(res.status === 200){
console.log('1st data')
axios.post(url, data, header)
.then(response => {
if (response.status === 200) {
console.log('2nd data')
} else {
console.log('2nd error')
}
});
}else{
console.log('1st error')
}
});