摘要:
最近,公司准备使用React Native开发一个档案APP,我在学习了一段时间之后,结合网上前辈们的资料,最终整理了一份基于React Native、Redux的demo。下面进入正题
安装模块
npm install --save-dev redux
npm install --save-dev react-redux
npm install --save-dev redux-logger
npm install --save-dev redux-devtools
npm install --save-dev redux-thunk
具体版本号如上图所示,另,React Native项目的版本号是0.57
新建ActionTypes.js文件
// 在使用redux过程中,需要给每个动作添加一个actionTypes类型
export const GET_CLASSIFIES = 'GET_CLASSIFIES';
新建CountAction.js文件,网络请求一般都是放在action文件中
import {
GET_CLASSIFIES
} from './actiontypes/ActionTypes';
import {
QUERY_CLASSIFY
} from '../api/';
// 每个页面是可以有多个action的,只需要在页面中引入就好
const getClassifies = () => {
return async (dispatch) => {
let msg = await fetch(QUERY_CLASSIFY, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
}).then(response => response.json());
dispatch({
type: GET_CLASSIFIES,
data: msg
})
}
};
export {
getClassifies
}
/**
* react-redux的执行流程:
* component -> actionCreator(data) -> reducer -> component
*/
新建RootReducer.js文件
// RootReducer中存放的是各个页面的Reducer,推荐的做法是
// 一个页面公用一个Reducer,便于之后的管理
// Reducer是纯函数,里面不应该有过多的逻辑
import {combineReducers} from 'redux';
import CountReducer from './CountReducer';
// 取决于这里加入了多少 reducer
const RootReducer = combineReducers({
countReducer: CountReducer
});
export default RootReducer;
新建CountReducer.js文件
import {
GET_CLASSIFIES
} from '../actions/actiontypes/ActionTypes';
// 原始默认state
const defaultState = {
count: 5,
factor: 1,
data: ''
};
export default function counter(state=defaultState, action) {
switch(action.type) {
case GET_CLASSIFIES:
return {...state, count: state.count + state.factor, data: action.data};
default:
return state;
}
}
新建ConfigureStore.js文件
import {
createStore,
applyMiddleware,
compose
} from 'redux';
// redux-thunk是用来发送异步请求的中间件,用了thunk之后,
// 一般的操作是将网络请求的方法放在action中
import thunk from 'redux-thunk';
// redux-logger是打印logger的中间件
import createLogger from 'redux-logger';
import RootReducer from '../reducers/RootReducer';
const configureStore = preloadState => {
// createStore(reducer, [initState, enhancer]):创建一个Redux Store来存放所有的
// state,一个应用只能有一个store。函数返回store对象.enhancer:一个中间件
return createStore(
RootReducer,
preloadState,
compose(
applyMiddleware(createLogger, thunk)
)
);
};
const store = configureStore();
export default store;
新建CountButton.js页面
import React, {Component} from 'react';
import {
View,
Text,
Button,
FlatList,
StyleSheet
} from 'react-native';
import {connect} from 'react-redux';
import {
getClassifies
} from '../../redux/actions/CountAction';
class CountButton extends Component {
constructor(props) {
super(props);
}
_onPressDec() {
this.props.dispatch(getClassifies());
}
render() {
const {msg, data} = this.props.countReducer.data;
return (
<View style={styles.container}>
<View style={styles.buttonContainer}>
<Button
title='decrement'
onPress={() => this._onPressDec()}/>
</View>
<Text>{msg}</Text>
<FlatList
data={data}
renderItem={({item}) => <Text style={styles.item}>{item.id} {item.phone}</Text>}
keyExtractor={(item) => item.id.toString()}/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
marginTop: 40,
alignItems: 'center',
justifyContent: 'center',
},
buttonContainer: {
margin: 10
},
item: {
padding: 10,
fontSize: 18,
height: 44
}
});
const mapStateToProps = state => {
const {countReducer} = state;
return {
countReducer
};
};
// 连接React组件与Redux store
export default connect(mapStateToProps)(CountButton);
总结,我这面主要是提供一份完整的demo,至于redux中的action,reducer之间的管理,以及redux的实现原理,网上资料超级多,请自行查找,此处不在赘述。
项目地址:https://github.com/SUNOW2/RnDemo