正如Malvolio所说,在Promise中定义catch
方法时的预期行为,其中引发的所有内容都会被抓取。
对我来说,处理这种行为的最好方法是使用Redux,因为它会分离你的组件和他们需要的数据之间的关系。即使我并不真正了解你在React生态系统中的知识,并且你说它只是一个原型,我觉得最好使用这种模式,越快越好。 Redux后面有the motivations,值得一看。
要开始使用,您必须使用create a redux store,它可以由多个缩减器组成,这些缩减器将代表您的状态的小型独立分区,以允许进行非常受控制的访问。
您城镇减速可能看起来是这样,也将让你得到负荷和错误状态:
import { handleActions } from 'redux-actions'
const initialState = {
data: [],
isLoading: false,
err: null
}
export default handleActions({
FETCHING_TOWNS: state => ({ ...state, isLoading: true })
FETCH_TOWNS_SUCCESS: (state, { payload }) => ({ data: payload, isLoading: false, err: null })
FETCH_TOWNS_ERROR: (state, { payload }) => ({ data: [], err: payload, isLoading: false })
}, initialState)
下面是一个什么样的商店创建可能是一个例子,使用combineReducers
:
import { createStore, combineReducers, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'
import towns from './towns'
const reducers = combineReducers({
towns
})
const store = createStore(reducers, applyMiddleware(thunk))
export default store
要连接你的组件和reducer,你必须创建thunk操作(因此在商店中的中间件)。 请注意,这只是使用REDX处理副作用的一种方法!有很多方法可以解决这个问题,但这是最容易和最常见的方法之一。
import axios from 'axios'
import { createAction } from 'redux-actions'
const fetchingTowns = createAction('FETCHING_TOWNS')
const fetchTownsError = createAction('FETCH_TOWNS_ERROR')
const fetchTownsSuccess = createAction('FETCH_TOWNS_SUCCESS')
export const fetchTowns =() => dispatch => {
dispatch(fetchingTowns())
axios.get()
.then(response => dispatch(fetchTownsSuccess(response)))
.catch(error => {
dispatch(fetchTownsError(err))
Alert.alert(
'Download failed',
`Unable to download data from ${url}\nError: ${error}`,
[{text: 'OK'}]
)
});
}
为了使您的部件“连接”到你的店,这意味着他们将呈现再度他们的道具的变化之一,你必须在你的应用程序的顶层添加react-reduxProvider
组件,然后你可以装饰你的组件,只取得组件依赖的数据。
您的组件会看起来像这样,并且如果在渲染子组件时发生错误,它将不会被axios Promise拦截,因为它已从组件中分离出来。
import React from 'react'
import { View } from 'react-native'
import { connect } from 'react-redux'
@connect(state => ({
towns: state.towns.data
}), {
fetchTowns
})
class TownsList extends Component {
componentWillMount() {
this.props.fetchTowns()
}
render() {
const { towns } = this.props
return (
<View>
{towns.map(town => (
<TownComponent town={town} key={town.id}>
)}
</View>
)
}
}
我理解这可能是,如果你不熟悉所有的新的依赖和配置的它增加了位有点讨厌,但我可以向你保证,这是值得从长远来看!
ary你使用try块在代码中的任何地方? – Codesingh
@Codesingh不,在整个项目中搜索“try”关键字没有找到结果 –
你可以在承诺里面显示代码('then') –