是否有更好的方法来编写这部分代码?可以,但是随行人员抱怨说
'resp'已在较高范围中声明
在这部分
return parseJSON(resp).then((resp) => {
throw resp
})
这是完整的代码
componentDidMount = async () => {
const parseJSON = (resp) => (resp.json ? resp.json() : resp)
const checkStatus = (resp) => {
if (resp.status >= 200 && resp.status < 300) {
return resp
}
return parseJSON(resp).then((resp) => {
throw resp
})
}
const headers = {
'Content-Type': 'application/json'
}
try {
const data = await fetch('http://myurl/api', {
method: 'GET',
headers: headers
}).then(checkStatus)
.then(parseJSON)
this.setState({ data })
} catch (error) {
this.setState({ error })
}
}
答案 0 :(得分:1)
在同一行的以下行中,您有两个变量名resp
:
const checkStatus = (resp) => {
和return parseJSON(resp).then((resp) => {
。
更改其中之一。