react redux 二次開發流程

在一個大項目中如何引入redux及其相關技術棧(react-redux redux-thunk redux-immutable ),已經成爲react前端工程師不可或缺的技能,下面經過實現一個簡單的todolist效果,來介紹相關流程javascript

 

 

1.引入redux進行應用數據管理,安裝相關依賴

yarn add redux  react-redux redux-thunk redux-devtools-extension
通常目錄結構

 

2.建立好store.js、reducer.js、action.js、action-types.js

1)store.js
1 /*
2 redux最核心的管理對象store
3  */
4 import {createStore} from 'redux'
5 import reducer from './reducer'
6 
7 const  store = createStore(reducer, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__())
8 // 向外默認暴露store
9 export default  store

 2) reducer.jshtml

 1 import {CHANGEINPUT,ADDITEMS } from './action-types'
 2 
 3 const defalutState = {
 4     inputValue : 'wuxiaohui',
 5     list :[]
 6 }
 7 
 8 export default (state = defalutState,action) =>{
 9     if(action.type === CHANGEINPUT){
10         let newState = JSON.parse(JSON.stringify(state))//深拷貝
11         newState.inputValue = action.value
12         return newState
13     }
14     if(action.type === ADDITEMS){
15         let newState = JSON.parse(JSON.stringify(state))
16         newState.list.push(newState.inputValue)
17         newState.inputValue = ''
18         return newState
19     }
20 
21     return state
22 }

3)action.js前端

import {CHANGEINPUT,ADDITEMS } from './action-types'

export const inputChange = (e)=>({
    type:CHANGEINPUT,
    value:e.target.value
})

export const clickButton = ()=>({
    type:ADDITEMS
})

4)action-types.jsjava

/*
包含n個action type常量名稱的模塊
 */
export const CHANGEINPUT = 'change_input'
export const ADDITEMS = 'add_item'

3.建立todolistui組件

編寫TodolistUI.js,因爲沒有雙向綁定,經過onChange的inputChange事件拿到輸入值並經過inputValue傳回給輸入框,clickButton則是向list中追加輸入框中輸入的數據,輸入後清空。該邏輯在 reducer.js中體現,UI組件只負責展現。
 
//把TodoList改成UI組件-提升性能

import React from "react";

 const TodoListUI =(props)=>{
// 接收connect鏈接器映射傳遞的屬性和函數
    let {inputValue ,inputChange,clickButton,list} = props; 
    return (

        <div>
            <div>
                <input value={inputValue} onChange={inputChange} />
                <button onClick={clickButton}>提交</button>
            </div>
            <ul>
                {
                    list.map((item,index)=>{
                        return (<li key={index}>{item}</li>)
                    })
                }
            </ul>
        </div>
    );
}
export  default TodoListUI

4.引入react-redux進行應用數據管理

1)總入口中index.js中引入react-redux和容器組件APP
react-redux的核心:Provider(用於入口) 和 connect(用於數據和函數映射)
使用provider
/*
入口js
 */
import React from 'react';
import ReactDOM from 'react-dom';

import App from './containers/App';
import { Provider} from 'react-redux'
import store from './redux/store'

//<Provider>是一個提供器,只要使用了這個組件,組件裏邊的其它全部組件均可以使用store了
//聲明一個App容器組件,而後這個組件用Provider進行包裹。
const  AppList = (
    <Provider store={store}>
        <App />
    </Provider>
)
ReactDOM.render(AppList, document.getElementById('root'));
2)connect鏈接器(鏈接UI組件和redux中的action.js方法)成爲容器組件
connect-鏈接器用來將redux管理的state數據映射成UI組件的通常屬性(如輸入框的值)
connect-鏈接器用來將redux管理的包含diaptch代碼的函數映射成UI組件的函數屬性的函數
1.在redux目錄中的action.js定義UI組件要調用的方法,而後編寫好reducer的業務邏輯
2.在containers容器APP組件中 引入UI組件TodolistUI和action進行鏈接
import React from 'react'
import {connect} from 'react-redux'

import TodoListUI from '../components/TodoListUI'
import {inputChange,clickButton} from '../redux/actions'

/*
connect-鏈接器用來將redux管理的state數據映射成UI組件的通常屬性(如輸入框的值)
 指定向TodoList傳入哪些通常屬性(屬性值的來源就是store中的state)
 */
const stateToProps = (state)=>{
    return {
        inputValue : state.inputValue,
        list:state.list
    }
}

/*
connect-鏈接器用來將redux管理的包含diaptch代碼的函數映射成UI組件的函數屬性的函數
(如輸入的onChange事件)
能夠寫多個函數,用逗號隔開
 */
// 寫法1
// const dispatchToProps = (dispatch) =>{
//     return {
//         inputChange(e){
//             //派發action到store中:定義action 而後派發
//             //派發後就在reducer裏邊,編寫對應的業務邏輯了
//             let action = {
//                 type:'change_input',
//                 value:e.target.value
//             }
//             dispatch(action)
//         },
//         clickButton(){
//
//             let action = {type:'add_item'}
//             dispatch(action)
//         }
//     }
// }
//export default connect(stateToProps,dispatchToProps )(TodoListUI);

// 寫法2
export default connect(stateToProps,{inputChange,clickButton} )(TodoListUI);
5.引入 immutablejs
首先,咱們有必要來劃分一下邊界,哪些數據須要使用不可變數據,哪些數據要使用原生js數據結構,哪些地方須要作互相轉換
  • 在redux中,全局state必須是immutable的,這點毋庸置疑是咱們使用immutable來優化redux的核心
  • 組件props是經過redux的connect從state中得到的,而且引入immutableJS的另外一個目的是減小組件shouldComponentUpdate中沒必要要渲染,shouldComponentUpdate中比對的是props,若是props是原生JS就失去了優化的意義
  • 組件內部state若是須要提交到store的,必須是immutable,不然不強制
  • view提交到action中的數據必須是immutable
  • Action提交到reducer中的數據必須是immutable
  • reducer中最終處理state必須是以immutable的形式處理並返回
  • 與服務端ajax交互中返回的callback統一封裝,第一時間轉換成immutable數據

1)安裝相關依賴react

yarn add immutable  redux-immutable 

2)在reducer中 immutable的fromJs,把defalutState 轉爲immutable數據git

 1 // 引入fromJS 將state數據轉變爲 immutable對象
 2 const defalutState = fromJS({
 3     inputValue : 'wuxiaohui',
 4     list :[]
 5 });
 6 
 7 //immutablejs的相關接口——使用get 和set 方法來改變state
 8 export default (state = defalutState,action) =>{
 9     if(action.type === CHANGEINPUT){
10         // let newState = JSON.parse(JSON.stringify(state)) //深拷貝
11         // newState.inputValue = action.value
12         // return newState
13         return  state.set('inputValue',action.value)
14     }
15     if(action.type === ADDITEMS){
16         // let newState = JSON.parse(JSON.stringify(state))
17         // newState.list.push(newState.inputValue)
18         // newState.inputValue = ''
19         // return newState
20         
21         return state.merge({
22             'list': state.get('list').push(state.get('inputValue')),
23             'inputValue': ''
24         });
25 
26     }
27 
28     return state
29 }

3)在容器組件中App.js中映射時使用get獲取相關屬性值github

 1 /*
 2 connect-鏈接器用來將redux管理的state數據映射成UI組件的通常屬性(如輸入框的值)
 3  指定向TodoList傳入哪些通常屬性(屬性值的來源就是store中的state)
 4  */
 5 const stateToProps = (state)=>{
 6     return {
 7         // inputValue : state.inputValue,
 8         // list:state.list
 9         //由於引入了immutable,state 已變爲不可變對象只能調用get或set方法
10         inputValue : state.get('inputValue'),
11         list:state.get('list')
12     }
13 }
更多用法:
 

4)redux-immutable在reducer的處理ajax

combineReducers(reducers)
隨着應用變得愈來愈複雜,能夠考慮將 reducer 函數 拆分紅多個單獨的函數,拆分後的每一個函數負責獨立管理 state 的一部分

相似這樣redux

 1 import { combineReducers } from 'redux';
 2 import { reducer as headerReducer } from '../common/header/store';
 3 import { reducer as homeReducer } from '../pages/home/store';
 4 import { reducer as detailReducer } from '../pages/detail/store';
 5 import { reducer as loginReducer } from '../pages/login/store';
 6 
 7 const reducer = combineReducers({
 8    header: headerReducer,
 9    home: homeReducer,
10    detail: detailReducer,
11    login: loginReducer
12 });
13 
14 export default reducer;

 

假如咱們的reducer在header中,組件中獲取數據時,用get方法api

const mapStateToProps = (state) => {
    //inputValue是immutable對象,不能用state.header.inputValue的形式獲取,要用get()
      return  {
          inputValue :state.header.get('inputValue'),
          list:state.header.get('list')    
      }    
}

在使用了redux-immutable

1 //combineReducers再也不用rudux裏的,而是redux-immutable裏的,這樣combineReducers裏的對象就是一個immutable對象
2 //import {combineReducers} from 'redux'
3 import {combineReducers} from 'redux-immutable'
4 import {reducer as headerReducer} from '../common/header/store'
5 const reducer=combineReducers({
6     header:headerReducer
7 });
8 export default reducer;

獲取數據的時候用get(),或者getIn()--獲取結構化數據

1 const mapStateToProps = (state) => {    
2       return  {
3           //inputValue :state.header.get('inputValue'),
4          // list:state.header.get('list') 
5              inputValue :state.getIn(['header','inputValue']),
6              list:state.getIn(['header','list'])
7       }    
8 }
 
流程中例子詳見GitHub
相關文章
相關標籤/搜索