我有多个组件可以查询终结点以获取数据,并且我想以更通用的方式处理fetch()结果导致的拒绝和错误。此刻,我只是复制粘贴每个组件中的处理函数,所以我有这样的东西:
componentDidMount() {
fetch(...)
.then(res => {
handle success...
})
.then(null, rej => {
handle rejection - display some message to the user
set redirect to true in order to return a <Redirect.../> component
})
.catch(err => {
handle error - display message, potentially clear storage and redirect as for rejection
})
如何将拒绝和错误处理归纳为更高级别的组件