react native 之 redux 使用入門套路

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

相關文章
相關標籤/搜索