国家帐户编号:47228906名称:“ Senpai My Guy”召唤者等级:127
初始状态
class App extends Component {
constructor (props) {
super(props)
this.state = {
name: '',
summonerLevel: '',
accountId: 0
}
}
第一个请求
componentDidMount () {
var api_key = '';
axios
.get(
`https://na1.api.riotgames.com/lol/summoner/v3/summoners/by-name/Senpai%20My%20Guy?api_key=${api_key}`
)
.then(response => {
console.log(response.data)
console.log(response.data.name)
console.log(response.data.accountId)
console.log(response.data.summonerLevel)
this.setState({
name: response.data.name,
summonerLevel: response.data.summonerLevel,
accountId: response.data.accountId
})
console.log(this.state.accountId)
})
var account_Id = this.state.accountId
添加第二个请求
componentDidMount () {
var api_key = '';
axios
.get(
`https://na1.api.riotgames.com/lol/summoner/v3/summoners/by-name/Senpai%20My%20Guy?api_key=${api_key}`
)
.then(response => {
console.log(response.data)
console.log(response.data.name)
console.log(response.data.accountId)
console.log(response.data.summonerLevel)
this.setState({
name: response.data.name,
summonerLevel: response.data.summonerLevel,
accountId: response.data.accountId
})
console.log(this.state.accountId)
})
var account_Id = this.state.accountId
axios
.get(
`https://na1.api.riotgames.com/lol/match/v3/matchlists/by-account/${account_Id}?api_key=${api_key}`
)
.then(response => {
console.log(response.data.matches)
})
.catch(err => {
console.log(err)
})
}
GET https://na1.api.riotgames.com/lol/match/v3/matchlists/by-account/0?api_key= 404 (Not Found)
Error: Request failed with status code 404
at createError (createError.js:16)
at settle (settle.js:18)
at XMLHttpRequest.handleLoad (xhr.js:77)
答案 0 :(得分:0)
setState
是异步的,因此如果您尝试在使用状态后直接访问它,则状态不会被更新。您的axios
请求也是异步的,因此您需要确保第一个请求已完成,然后再启动第二个请求。
您可以在第二个请求中使用响应中的accountId
变量。
示例
componentDidMount() {
var api_key = "...";
axios
.get(
`https://na1.api.riotgames.com/lol/summoner/v3/summoners/by-name/Senpai%20My%20Guy?api_key=${api_key}`
)
.then(response => {
var { name, summonerLevel, accountId } = response.data;
this.setState({ name, summonerLevel, accountId });
axios
.get(
`https://na1.api.riotgames.com/lol/match/v3/matchlists/by-account/${accountId}?api_key=${api_key}`
)
.then(response => {
console.log(response.data.matches);
})
.catch(err => {
console.log(err);
});
});
}