Guest User

Untitled

a guest
Jul 23rd, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.92 KB | None | 0 0
  1. ### 全局错误处理
  2.  
  3. ``` js
  4. /* eslint-disable */
  5. import { setGlobalHandler } from 'ErrorUtils';
  6. /* eslint-enable */
  7.  
  8.  
  9. setGlobalHandler((error) => console.warn(error)); // eslint-disable-line
  10.  
  11. ```
  12.  
  13. ### Navigation
  14.  
  15. ```
  16.  
  17. const AppNavigator = StackNavigator(routes, {
  18. headerMode: 'none'
  19. });
  20.  
  21. const defaultGetStateForAction = AppNavigator.router.getStateForAction;
  22.  
  23. AppNavigator.router.getStateForAction = (action, state) => {
  24. if (action.type && action.type.startsWith('Nav')) {
  25. // console.log(action);
  26. // 所有的导航事件都会走这里,可以定制一些东西,
  27. // action 是跳转动作,state是当前StackNavigator的状态
  28. const routeName = action && action.routeName;
  29. const globalState = store && store.getState();
  30. const profile = globalState ? globalState.user.profile : {};
  31. const features = profile.features || [];
  32. if (!isPrivileged(routeName, features)) {
  33. setTimeout(() => {
  34. dispatchErrorMessage('没有权限访问此页面');
  35. }, 0);
  36. return state;
  37. }
  38. }
  39. return defaultGetStateForAction(action, state);
  40. };
  41.  
  42.  
  43. class AppNavigation extends Component {
  44. state = {
  45. appState: AppState.currentState
  46. }
  47. componentDidMount() {
  48. if (Platform.OS === 'ios') {
  49. JAnalyticsModule.setup({ appKey: 'xxxxxxxxxxxxxxx' });
  50. }
  51. if (Platform.OS !== 'ios') {
  52. RNSegmentIO.setup('xxxxxxxxxxxxxxxxxxx');
  53. }
  54. BackHandler.addEventListener('hardwareBackPress', () => {
  55. if (this.props.navigationState.index === 0 || this.props.navigationState.routes[1].routeName === 'Initial') {
  56. Alert.alert(
  57. '确认要退出么?',
  58. '',
  59. [
  60. { text: '暂时不', onPress: () => { }, style: 'cancel' },
  61. { text: '退出', onPress: () => BackHandler.exitApp() },
  62. ]
  63. );
  64. } else {
  65. this.props.dispatch(NavigationActions.back(null));
  66. }
  67. return true;
  68. });
  69. AppState.addEventListener('change', this._handleAppStateChange);
  70. }
  71.  
  72. _handleAppStateChange = (nextAppState) => {
  73. if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') {
  74. if (Platform.OS === 'ios') {
  75. JPushModule.setBadge(0, () => { });
  76. }
  77. }
  78. this.setState({ appState: nextAppState });
  79. }
  80. render() {
  81. const { dispatch, navigationState } = this.props;
  82. return (
  83. <AppNavigator
  84. navigation={
  85. addNavigationHelpers({
  86. dispatch,
  87. state: navigationState,
  88. })
  89. }
  90. />
  91. );
  92. }
  93. }
  94. ```
  95.  
  96. ### localstore
  97. ```
  98. import { AsyncStorage } from 'react-native';
  99. import Storage from 'react-native-storage';
  100.  
  101. export default new Storage({
  102. storageBackend: AsyncStorage,
  103. defaultExpires: 1000 * 3600 * 24 * 30
  104. });
  105.  
  106.  
  107. export class FakeApi {
  108. // the url should be added the id, getting the specific value
  109. static async get(url) {
  110. try {
  111. const data = await storage.load({
  112. key: url
  113. });
  114. return data || {};
  115. } catch (error) {
  116. return {};
  117. }
  118. }
  119.  
  120. static async put(url, body) {
  121. storage.save({
  122. key: url,
  123. data: body
  124. });
  125. }
  126.  
  127. }
  128. ```
  129.  
  130. fetch
  131.  
  132. ```
  133.  
  134. export const errorInterceptor = new Interceptor({
  135. fetchError: {
  136. id: 1,
  137. requestError(error) {
  138. // Alert.alert('请求出错', '请求地址或网络错误');
  139. dispatchErrorMessage('请求失败,当前网络异常请稍候再试');
  140. // loadFinished();
  141. return Promise.reject(error);
  142. },
  143. error(res) {
  144. // throw new RemoteAPIError(res.url, res.status);
  145. // 在生产环境不显示错误的 URL
  146.  
  147. const url = ENV === 'prod' ? '' : res.url;
  148. const errorMessage = ENV === 'prod' ? `服务器未知错误(${res.status}),请稍后尝试` : `url: ${url}, status: ${res.status}`;
  149. if (res.status >= 500) {
  150. return Promise.reject(res.message || errorMessage);
  151. }
  152. if (res.status === 401) {
  153. token.clear();
  154. token.autoLogin = false;
  155. const globalState = store && store.getState();
  156. const routes = globalState.nav.routes;
  157. const currentPage = routes[routes.length - 1].routeName;
  158. if (currentPage && currentPage !== 'Initial') {
  159. store.dispatch(LOGOUT.request());
  160. dispatchErrorMessage('Token 过期,请重新登录 APP');
  161. }
  162. return Promise.reject(res.message);
  163. }
  164. if (res.text) {
  165. res.json().then((data) => {
  166. if (data && data.message) {
  167. dispatchErrorMessage(data.message);
  168. return Promise.reject(new RemoteAPIError(url, res.status));
  169. }
  170. dispatchErrorMessage(errorMessage + data);
  171. return Promise.reject(new RemoteAPIError(url, res.status));
  172. }).catch(err => {
  173. // console.log('promise reject err');
  174. });
  175. } else {
  176. dispatchErrorMessage(errorMessage);
  177. return Promise.reject(new RemoteAPIError(url, res.status));
  178. }
  179. }
  180. },
  181. codeError: {
  182. id: 2,
  183. success(data) {
  184. if (data.code === -2 || data.code === 401) {
  185. token.clear();
  186. token.autoLogin = false;
  187. store.dispatch(LOGOUT.request());
  188. dispatchErrorMessage('Token 过期,请重新登录 APP');
  189. return Promise.reject(data.message);
  190. }
  191.  
  192. if (data.code !== 0) {
  193. dispatchErrorMessage(data.message);
  194. return Promise.reject(data.message);
  195. }
  196.  
  197. return Promise.resolve(data.data);
  198. }
  199. }
  200. });
  201.  
  202.  
  203.  
  204. import { tokenInterceptor } from './token';
  205. import { errorInterceptor } from './error';
  206. import { timeoutInterceptor } from './timeout';
  207. import { netInfoInterceptor } from './netInfo';
  208.  
  209. export const interceptors = tokenInterceptor
  210. .merge(netInfoInterceptor)
  211. .merge(errorInterceptor)
  212. .merge(timeoutInterceptor);
  213.  
  214.  
  215.  
  216. import { FetchClient } from 'intercept-fetch';
  217. import { interceptors } from './interceptors';
  218. import { config } from './config';
  219. import './fetch';
  220.  
  221. const fetchClient = new FetchClient();
  222. fetchClient.timeout = config.timeout;
  223. fetchClient.setInterceptors(interceptors);
  224.  
  225. export default fetchClient;
  226. ```
Add Comment
Please, Sign In to add comment