[英]Problem with nested fetch request in React
New to React, I'm currently trying to create a data table with data from an API. 我是React的新手,目前正在尝试使用API中的数据创建数据表。 I want to have a first fetch, and then run another with response from the first (id) in order to complete my table.
我想要进行第一次提取,然后使用第一个(id)的响应运行另一个,以完成我的表。
Here is my code : 这是我的代码:
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 })
})
}
With this code, I have the data I want to render my table but I need to run another fetch to get other info with the id coming from the first request. 有了这段代码,我有了要呈现表的数据,但是我需要运行另一个访存来获取ID为来自第一个请求的其他信息。
How can I do that nested fetch request ? 我该如何执行嵌套的提取请求?
Thanks a lot, 非常感谢,
Matthieu 马修
You can easily manage this with async/await
: 您可以使用
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 });
}
You can read more about async function . 您可以阅读有关异步功能的更多信息。
You can write the code as below. 您可以编写如下代码。
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 });
});
});
Hope this will work for you! 希望这对您有用!
@JourdanM, you should return a new fetch
request from one of the then
handlers. @JourdanM,您应该从
then
处理程序中返回一个新的fetch
请求。 I've made a simple snippet for you. 我为您做了一个简单的摘要。 There are no data validators and spinners.
没有数据验证器和微调器。 This is a simple showcase.
这是一个简单的展示。 =)
=)
A fetch
request returns a promise, and you can chain promises by simply returning them from the then
handlers. fetch
请求会返回一个承诺,您可以通过简单地从then
处理程序中返回它们来链接承诺。 Here is a good article about it, it has great examples: https://javascript.info/promise-chaining 这是一篇很好的文章,其中有很多示例: https : //javascript.info/promise-chaining
function fetchUser (user) { return fetch(`https://api.github.com/users/${user.login}`) } class User extends React.Component { state = { user: null } componentDidMount () { fetch("https://api.github.com/users") .then(response => response.json()) .then(users => fetchUser(users[0])) .then(response => response.json()) .then(user => { this.setState({user}) }) } render () { return ( <div> <pre>{JSON.stringify(this.state.user, null, 2)}</pre> </div> ) } } ReactDOM.render(<User />, document.querySelector("#root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root"></div>
You can also use axios like below 您也可以使用如下的axios
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')
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.