我有一个Web应用程序,当没有Internet连接时需要使用缓存的数据。现在,我可以在catch块中使用第二个fetch调用,使其运行良好,但是我觉得这不是正确的方法。
fetch(api)
.then(resp => resp.json())
.then(json => {
this.setState({
result: json.Results,
})
})
.catch(e => {
const options = {
cache: "force-cache"
}
fetch(api, options)
.then(resp => resp.json())
.then(json => {
console.log(`failed to fetch --- using cached data`)
this.setState({
result: json.Results,
})
})
.catch(e => {
console.error("Insufficient data")
})
})
有更好的方法吗?