redux是什么?他是一个state容器react
redux的运做方式是怎样的?git
接入方式:github
1. npm install 下列内容:npm
npm install --save redux npm install --save react-redux npm install --save-dev redux-devtools 当项目中用到了导航栏,就须要这样: npm install --save react-navigation-redux-helpers
2. 用<Provider/>包裹根组件, 将store传递给App框架redux
import {Provider} from 'react-redux';
import store from './store' const App = () => { return <Provider store={store}> <AppNavigator/> </Provider> };
3. 用connect方法, 包裹导航器组件,导出。connect($1,$2)($3) ,其中$1是state 到props 的映射,$2是dispatch 到props的映射, $3是当前组件app
例如:框架
export const middleware = createReactNavigationReduxMiddleware( state => state.nav, 'root', ); const AppWithNavigationState = createReduxContainer(RootNavigator,'root'); const mapStateToProps = state => ({ state: state.nav, // v2 }); export default connect(mapStateToProps)(AppWithNavigationState);
4. 建立store , 利用createStore()函数,传入reducers 做为参数ide
import {applyMiddleware,createStore} from 'redux' import thunk from 'redux-thunk' import reducers from '../reducer' import {middleware} from '../navigator/AppNavigator' // 如何自定义中间件 const logger = store => next => action => { if(typeof action === 'function'){ console.log('dispatch a function'); } else{ console.log('dispatching',action); } const result = next(action); console.log('nextState',store.getState()); } const middlewares = [ middleware, logger, thunk,//暂时没用到 ]; export default createStore(reducers,applyMiddleware(...middlewares));
5. 编写action, 通常action的类型集中定义到一个Types文件中函数
import Types from '../types'
export function onThemeChange(theme){ return { type: Types.THEME_CHANGE, theme:theme } }
6. 编写reducer, 他接收旧的state+action做为参数,而后产生新的statethis
例若有一个改变App主题色的redecer写法是这样
import Types from '../../action/types'; const defaultState = { theme: 'blue' }; export default function onAction(state = defaultState,action){ switch(action.type){ case Types.THEME_CHANGE: return { ...state, theme: action.theme, }; default: return state; } }
7.在页面中使用,从this.props获取状态容器中的数据, 从新渲染页面。这里原理是只要触发了action,就会更新state,从而更新界面
// 获取与当前页面有关的数据 _store(){ const {popular} = this.props; let store = popular[this.storeName]; if(!store){ store = { items:[], isLoading:false, projectModes:[], // 要显示的数据 hideLoadingMore:true, // 默认隐藏加载更多 } } return store; }
完整App见: https://github.com/nwgdegitHub/MK_GitHub_App