参考了React Native+React Navigation+Redux开发实用教程 这篇文章也能够参考参考react-native 中使用reduxreact
React Native+React Navigation+Redux搭建,搭建成功后尝试加一个小功能。
Page2
页面最上面是一个Text
,下面是经过createMaterialTopTabNavigator
建立了一组tab,如今经过点击Page1
中改变主题色
按钮,改变Page2
上Text
的文字颜色 redux
action记录全部你要作的意图,好比我要改变主题色react-native
export default {
THEME_CHANGE: "THEME_CHANGE",
}
复制代码
import Types from '../types';
/** * 第一个参数,string类型的type,第二个参数,根据本身须要的数据 * 主题变动 * @param theme * @returns {{type: string, theme: *}} */
export function onThemeChange(theme) {
return {type: Types.THEME_CHANGE, theme: theme}
}
复制代码
/** * 全部的action,对外使用 */
import { onThemeChange } from './theme/index'
export default{
onThemeChange
}
复制代码
reducer 就是一个纯函数,接收旧的 state 和 action,返回新的 state。 (previousState, action) => newState
函数
import Types from '../../action/types';
const defaultState = {
theme: 'blue'
}
export default function onAction(state = defaultState, action) {
switch (action.type) {
case Types.THEME_CHANGE:
//返回新的state,新的state携带theme属性
return {
...state,
theme: action.theme
}
default:
return state;
}
}
复制代码
import {combineReducers} from 'redux'
import theme from './theme'
import {rootCom, RootNavigator} from '../../navigators/AppNavigators';
//将全部的redux聚合
//1.指定默认state
const navState = RootNavigator.router.getStateForAction(RootNavigator.router.getActionForPathAndParams(rootCom));
/** * 2.建立本身的 navigation reducer, */
const navReducer = (state = navState, action) => {
const nextState = RootNavigator.router.getStateForAction(action, state);
// 若是`nextState`为null或未定义,只需返回原始`state`
return nextState || state;
};
/** * 3.合并reducer * @type {Reducer<any> | Reducer<any, AnyAction>} */
const index = combineReducers({
nav: navReducer,
theme: theme,
});
export default index;
复制代码
Page1
中的点击事件里,触发action的onThemeChange事件,并将色值做为参数传递进去。dispatch出state(包含了theme字段)
Page2
中接收到事件后,取出state中的theme,关联到其
props
里面,这样
Text
的文字颜色就改变了
const mapDispatchToProps = dispatch => ({
onThemeChange: (theme) => {
return dispatch(actions.onThemeChange(theme));
},
});
复制代码
export function onThemeChange(theme) {
return {type: Types.THEME_CHANGE, theme: theme}
}
复制代码
const defaultState = {
theme: 'blue'
}
export default function onAction(state = defaultState, action) {
switch (action.type) {
case Types.THEME_CHANGE:
//返回新的state,新的state携带theme属性
return {
...state,
theme: action.theme
}
default:
return state;
}
}
复制代码
const mapStateToProps = state => ({
//新的state里有theme属性(./theme/index.js),携带了theme字段
//最后theme的值会关联到props的theme
theme: state.theme.theme,
});
...
<Text style={{
color: theme
}}>6666</Text>
复制代码
结束post