修復(fù)1個(gè)簡單bug,在Android手機(jī)里因?yàn)橛?code>Back按鍵,所有需要特殊處理,直接貼代碼如下:
修改app/navigation/index.js添加如下代碼
componentWillMount() {
if (Platform.OS === 'android') {
BackAndroid.addEventListener('hardwareBackPress', this.onBackAndroid);
}
}
componentWillUnmount() {
if (Platform.OS === 'android') {
BackAndroid.removeEventListener('hardwareBackPress', this.onBackAndroid);
}
}
onBackAndroid = () => { return Actions.pop()}
其實(shí)就是綁定一個(gè)事件處理而已,如果應(yīng)用原生Nav的話,一般要在pop的時(shí)候判斷棧長度是否為0也即是否在首頁,不然會(huì)錯(cuò)處,原生Android返回鍵是退出應(yīng)用。另外這里的Platform.OS不判斷也可以的,以為IOS實(shí)現(xiàn)為空,無所謂的,這里寫出來只是順便介紹Platform。
另外修改了部分代碼以實(shí)現(xiàn)分頁查找:
修改了app/home/index.js
render() {
const {isFetching, movies} = this.props;
if (isFetching && !movies.subjects) {
return <Loading />
}
this.state.data = this.state.data.concat(movies.subjects)
return (
<ListView dataSource={this.state.dataSource.cloneWithRows(this.state.data)} renderRow={this._renderRow.bind(this)}
enableEmptySections={true}
onEndReached={this._handleLoadMore.bind(this)}
onEndReachedThreshold={10}
initialListSize={2}
refreshControl={
<RefreshControl
refreshing={isFetching}
onRefresh={this._onRefresh.bind(this)}
color="#8CD790"
/>
}
renderFooter={() => this.props.hasMore ? <LoadMore active={this.props.isFetching}/> : null }
renderHeader={() => {
return (
<View style={styles.listViewTitle}>
<Text>{movies.title}</Text>
</View>
)
}}
/>
);
}
添加下拉刷新refreshControl組件以及上拉加載下一頁:
onEndReached={this._handleLoadMore.bind(this)}
onEndReachedThreshold={10}
//對應(yīng)如下函數(shù)
_onRefresh() {
// 刷新
const {dispatch} = this.props;
this.state.data = [];
dispatch(fetchMovies())
}
_handleLoadMore() {
// 加載更多
if (this.props.hasMore) {
const {dispatch, movies} = this.props;
let start = movies.start + movies.count;
dispatch(fetchMovies(start))
}
}
app/home/reducer.js
export function moviesReducer (
state={
isFetching: true,
hasMore: true,
movies: {}
}, action
) {
switch (action.type) {
case REQUEST_MOVIES:
return Object.assign({}, state, {
isFetching: true,
})
case RECEIVE_MOVIES:
const {movies} = action;
return Object.assign({}, state, {
movies: action.movies,
isFetching: action.isFetching,
hasMore: (movies.start + movies.count) < movies.total
})
default:
return state
}
}
簡單處理了一下,不夠嚴(yán)格,請依據(jù)實(shí)際業(yè)務(wù)自行修改。
還存在一些bug,有時(shí)間在整吧。寫到這里其實(shí)剩下的工作就很簡單了,藍(lán)圖已畫好,只需要根據(jù)需要的顏色按需涂上即可,先根據(jù)自己的業(yè)務(wù)分解action,定義constant,分發(fā)函數(shù)reducer,組件渲染然后connect到store,寫style,ok一個(gè)功能完成,就是這么簡單。
另外如果組件頁面變多,功能比較復(fù)雜,其實(shí)還可以優(yōu)化,從前面的代碼也可以看出,很多代碼其實(shí)都是相似的,這里這么寫只是可以更好的了解redux,程序員當(dāng)然是最懶的那一類人了,github上還有很多組件可以節(jié)省代碼時(shí)間,比如redux-actionshttps://github.com/acdlite/redux-actions可以生成具有一定規(guī)范的action,這樣就可以節(jié)省很多代碼了,諸如此類就不一一舉例了。
最后不要忘了test,測試用例還是要寫的,不要以為像這樣分割的代碼就不好測試了,應(yīng)用了redux之后寫測試反而會(huì)變得簡單了,因?yàn)槎际呛瘮?shù),各種js測試工具都是可以用的,比如mock等等,github上有很多測試第三方組件,搜一搜就是了。redux的另一特點(diǎn)就是可以時(shí)間旅行,比如可以回溯state重新測試、還可以在state里添加時(shí)間描述來測試性能,可以recordstate時(shí)間流來進(jìn)行壓力測試等等。(其實(shí)我沒有實(shí)踐過,不對的話當(dāng)我瞎說。。)