開(kāi)發(fā)中遇到需要在網(wǎng)絡(luò)請(qǐng)求錯(cuò)誤的時(shí)候提供一個(gè)統(tǒng)一的界面,結(jié)合Redux和一個(gè)封裝好的組件,很好處理.這個(gè)組件在iReading和reddit的app里面都使用過(guò),使用比較簡(jiǎn)單
直接參照ireading代碼
github:react-native-root-toast
安裝 需要這個(gè)組件
在./app/utils/ToastUtils.js文件中定義了方法
import {
Platform
} from 'react-native';
import Toast from 'react-native-root-toast';//導(dǎo)入組件
let toast;
//短時(shí)間提示的方法
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
});
};
//長(zhǎng)時(shí)間提示的方法
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的中間件來(lái)處理具體的邏輯,所以網(wǎng)絡(luò)請(qǐng)求處理的問(wèn)題也在saga里.如果沒(méi)有使用redux-saga這部分放到actions里做也是可以的,reddit好像是這么搞的.或者你可以看看ireading的以前使用redux-thunk的版本.
./app/sagas/read.js
import { toastShort } from '../utils/ToastUtil';//導(dǎo)入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); //錯(cuò)誤處理
}
} catch (error) {
yield put(receiveArticleList([], typeId));
toastShort('網(wǎng)絡(luò)發(fā)生錯(cuò)誤,請(qǐng)重試');//還是錯(cuò)誤處理
}
}
效果嘛,看組件 github的圖片

Toast圖片
圖太大,gif還不知道怎么改大小.