React-native中的弹窗提示组件

开发中遇到需要在网络请求错误的时候提供一个统一的界面,结合Redux和一个封装好的组件,很好处理.这个组件在iReading和reddit的app里面都使用过,使用比较简单
直接参照ireading代码

github:react-native-root-toast

安装 需要这个组件

在./app/utils/ToastUtils.js文件中定义了方法

import {
  Platform
} from 'react-native';
import Toast from 'react-native-root-toast';//导入组件

let toast;
//短时间提示的方法
export const toastShort = (content) => {
  if (toast !== undefined) {
    Toast.hide(toast);
  }
  toast = Toast.show(content.toString(), {
    duration: Toast.durations.SHORT,
    position: Platform.OS === 'android' ? Toast.positions.BOTTOM : Toast.positions.CENTER,
    shadow: true,
    animation: true,
    hideOnPress: true,
    delay: 0
  });
};
//长时间提示的方法
export const toastLong = (content) => {
  if (toast !== undefined) {
    Toast.hide(toast);
  }
  toast = Toast.show(content.toString(), {
    duration: Toast.durations.LONG,
    position: Platform.OS === 'android' ? Toast.positions.BOTTOM : Toast.positions.CENTER,
    shadow: true,
    animation: true,
    hideOnPress: true,
    delay: 0
  });
};

由于ireading的最新版改为使用redux-saga的中间件来处理具体的逻辑,所以网络请求处理的问题也在saga里.如果没有使用redux-saga这部分放到actions里做也是可以的,reddit好像是这么搞的.或者你可以看看ireading的以前使用redux-thunk的版本.

./app/sagas/read.js

 import { toastShort } from '../utils/ToastUtil';//导入toast
import { request } from '../utils/RequestUtil';
import { WEXIN_ARTICLE_LIST } from '../constants/Urls';
import { fetchArticleList, receiveArticleList } from '../actions/read';

export function* requestArticleList(isRefreshing, loading, typeId, isLoadMore, page) {
  try {
    yield put(fetchArticleList(isRefreshing, loading, isLoadMore));
    const articleList = yield call(request,
      `${WEXIN_ARTICLE_LIST}?typeId=${typeId}&page=${page}`,
      'get');
    yield put(receiveArticleList(articleList.showapi_res_body.pagebean.contentlist, typeId));
    const errorMessage = articleList.showapi_res_error;
    if (errorMessage && errorMessage !== '') {
      yield toastShort(errorMessage); //错误处理
    }
  } catch (error) {
    yield put(receiveArticleList([], typeId));
    toastShort('网络发生错误,请重试');//还是错误处理
  }
}

效果嘛,看组件 github的图片

Toast图片

图太大,gif还不知道怎么改大小.

结束

你可能感兴趣的:(React-native中的弹窗提示组件)