![](/img/trans.png)
[英]How to pass state/data from one component to another in React.js (riot api specifically)
[英]How to fetch the data from one api store into state and then pass this data into another api
class myFetchData extends Component {
constructor(props){
super(props)
this.state = {
data : [],
Issuer_News : []
}
}
componentDidMount(){
this.setState({loading : true})
axios.post('https://bqskvn9laah.execute-api.ap-south-1.amazonaws.com/Dev/datalist',{
DATA: this.state.data
}).then((response) => {
this.setState({data : res, number_of_data : response.data[1].total_data_issued_by_the_company,loading : false})})
.catch(err => console.log(err))
fetch(`https://gnews.io/api/v3/search?q=${this.state.data.Issuer_Name}&max=5&token=52498bb02769e98d131156c2648628ca`)
.then( response => response.json())
.then(data => this.setState({Issuer_News : data.articles}))
}
我想要来自 API 1 的数据并将数据从 API 1 传递到 API 2 但this.state.data
返回undefined
。
在 ReactJS 中,setState 和 fetch 函数都是异步的,所以这就是你未定义的原因。 因为 API 2 可以在返回 API 1 的成功承诺之前运行。 我更喜欢在成功承诺中调用 API 2 的 fetch 函数。 像这样
axios.post('https://bqskvn9laah.execute-api.ap-south-1.amazonaws.com/Dev/datalist',{
DATA: this.state.data
}).then((response) => {
this.setState({data : res, number_of_data :
response.data[1].total_data_issued_by_the_company,loading : false})
fetch(`https://gnews.io/api/v3/search?q=${response.data.Issuer_Name}&max=5&token=52498bb02769e98d131156c2648628ca`)
.then( response => response.json())
.then(data => this.setState({Issuer_News : data.articles}))
}).catch(err => console.log(err))
我建议您使用一些状态管理器库,如 redux、redux-saga 来更轻松地控制您的 api 调用流程
在这种情况下,如果要链接 api 调用,则需要在接收数据的第一个 api 的 then() 块的 setState 方法中调用第二个 api。 setState方法有一个变体,您可以在其中将函数作为参数传递,并确保仅在调用 setState 时才运行该函数。
如果您使用this.state.data
仅在 then() 块中进行调用是this.state.data
。 您需要将 fetch 调用放在 setState 的回调函数中。 如果不想使用回调函数变体,那么直接在 then() 方法中使用响应变量即可。
假设axios.post
是第一个 API 而fetch
是第二个
componentDidMount(){
this.setState({loading : true})
axios.post('<yourUrl>', {
...
}).then((response) => {
this.setState({<setYourState>}, () => {
fetch(`https://gnews.io/api/v3/search?q=${this.state.data.Issuer_Name}&max=5&token=52498bb02769e98d131156c2648628ca`)
.then( response => response.json())
.then(data => this.setState({Issuer_News : data.articles}))
}
})
})
.catch(err => console.log(err))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.