參考了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