redux的簡單使用

redux的基本使用

store文件夾

  • index.js
// 1. 引入redux的建立store方法 createStore
  import { createStore } from 'redux';
  
  // 2. 引入reducer
  import reducer from 'reducer';
  
  // 3. 使用createStore方法,並傳入reducer
  const store = createStore(
    reducer,
    window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__() // 使用redux谷歌插件
  );
  
  // 4. 講store暴露出去
  export default store;
  • reducer.js
// 引入actionTypes.js
  import { ACTION_TYPE } from './actionTypes'
  
  // 1. 定義state的默認值
  const defaultState = {
      data: []
  };
  
  // 2. 暴露函數
  export default (state = defaultState, action) => {
   // 4. 經過接收的action參數判斷下一步操做
   if(action.type === ACTION_TYPE) {
     // 5. 深拷貝state
     const newState = JSON.parse(JSON.stringify(state));
     
     // 6. 對newState的數據進行修改
     newState.data = action.value;
     
     // 7. 將newState返回
     return newState;
   }
      // 3. 返回state
      return state;
  }
  • actionTypes.js
//統一管理redux的actionde type屬性,杜絕代碼錯誤,有利於工程化
  export const ACTION_TYPE = 'action_type;
  • actionCreators.js
// 引入actionTypes.js
  import { ACTION_TYPE } from './actionTypes'
  // action建立器,有利於自動化測試
  export const getAction = (value) => ({
    type: ACTION_TYPE,
    value
  })

Component.js

import React, { Component } from 'react';
  // 1. 引入store
  import store from './store';
  
  // 2. 引入actionCreators.js中建立action的方法
  import { getAction } from './store/actionCreators';
  
  class App extends Component {
    render(){}
    
    handelGetAction(){
      const value = 'aa';
       
      // 3. 調用action建立方法
      const action = getAction(value);
      
      // 4. 派發action
      store.dispatch(action);
    }
  }
相關文章
相關標籤/搜索