Ped*_*ira 2 httprequest promise async-await reactjs axios
我正在尝试从 API 获取图像数据。为此,我首先需要获取它的 ID,然后使用它来获取图像。为了保持干净的代码,我使用了一个函数来做到这一点,当我尝试将响应返回给我调用该函数的组件时遇到了问题。
获取下一个图像数据
export const getNextImageData = () => {
const apiToken = lscache.get('apiToken')
return(
axios({
method: 'get',
url: 'https://myapiurl/images/',
params: {
limit: '1',
doc_cat: ''
},
responseType: 'json'
})
.then(response => {
lscache.set('imageData', response, 30)
axios({
method: 'get',
url: 'https://myapiurl/images/' + response.data[0].id + '/',
})
.then(response => {
return(response.data)
})
})
)
}
Run Code Online (Sandbox Code Playgroud)
我的课
class MyClass extends Component {
constructor(props){
super(props);
this.state = {
image: undefined
}
}
async componentDidMount() {
const data = await getNextImageData()
this.setState({
image: data,
})
}
render() {
// something
}
}
Run Code Online (Sandbox Code Playgroud)
我从返回中什么也没收到,当我将代码直接粘贴到我的组件中时,它工作正常,但我想在函数中使用它
我错误地嵌套它,您没有then在另一个内部使用 a then,而是在同一级别使用它们。每个 axios 调用都遵循一个return语句。这样做我什至不需要使用 async/await,我使用了另一个promise.
获取下一个图像数据
export const getNextImageData = () => {
const apiToken = lscache.get('apiToken')
return axios({
method: 'get',
url: 'https://myapiurl/images/',
params: {
limit: '1',
doc_cat: ''
},
responseType: 'json'
})
.then(response => {
lscache.set('imageData', response, 30)
return axios({
method: 'get',
url: 'https://myapiurl/images/' + response.data[0].id + '/',
})
})
.then(response => {
return response.data
})
}
Run Code Online (Sandbox Code Playgroud)
我的课
class MyClass extends Component {
constructor(props){
super(props);
this.state = {
image: undefined
}
}
componentDidMount() {
getNextImageData()
.then(data => {
this.setState({
image: data,
})
})
}
render() {
// something
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4398 次 |
| 最近记录: |