react 優化(用於記錄)

reducer拆分

  • 在對應的組件的文件下建立store文件
  • 把主store的reducer.js 作變更
import { combineReducers } from'redux';
import headerReducer from '../common/header/store/reducer';
const reducer = combineReducers({
    header:headerReducer
});
export default reducer;
  • 組件對應獲取store的變動
const mapStateToProps = (state) => {
    return {
        focuse:state.header.focuse,
        list:state.header.list
    }
};

組件 store作一個公共的出口文件 index.js

//組件下的store文件下的index.js
import reducer from './reducer';
import * as actionCreators from './actionCreators';
import * as actionTypes from './actionTypes'
export { reducer , actionCreators ,  actionTypes} ;
//項目主store文件下的reducer.js
import { combineReducers } from'redux';
import { reducer as headerReducer } from '../common/header/store';//as 取別名
const reducer = combineReducers({
    header:headerReducer
});
export default reducer;
//組件文件中作修改
import { actionCreators } from './store'
const mapStateToProps = (state) => {
    return {
        focuse:state.header.focuse,
        list:state.header.list
    }
};
const mapDispatchToProps = (dispatch) => {
    return {
        changeFocuse () {
            store.dispatch(actionCreators.changeFocuse())
        },
        changeBlue () {
            store.dispatch(actionCreators.changeBlur())
        }
    }
}

reducer不能直接修改store中的state,解決辦法引入imutable.js

  • 安裝immutable yarn add immutable
  • 使用
//reducer.js
import { fromJS }  from 'immutable';
//轉化state對象爲immutabel對象
const defaultState = fromJS({
    focuse:false,
    list:[]
});
//組件中的使用就須要改變,由於state.header變成了immutable對象,就不能直接使用.的方式獲取,要用get(屬性)來獲取
const mapStateToProps = (state) => {
    return {
        //老的
        //focuse:state.header.focuse,
        //list:state.header.list,
        focuse:state.header.get('focuse'),
        list:state.header.get('list')
    }
};
//要改變state的數據也應該爲immutable對象
//例如
import {fromJS} from 'immutable';
export const initList = (list) => ({
    type:actionTypes.INIT_LIST,
    list:fromJS(list)
})
  • reducer.js中設置state值的時候就不用深拷貝了,直接使用set('屬性',值),值必須是immutable對象
export default ( state = defaultState , action ) => {
    switch (action.type){
        case actionTypes.CHANGE_FOCUSE:
            return state.set("focuse",true);
        case actionTypes.CHANGE_BLUR:
            return state.set("focuse",false);
        case actionTypes.INIT_LIST:
            return state.set("list",action.list);
        default:
            return state
    }

}
  • 上面雖然使用了immutable,可是隻是header下的數據纔是immutable對象,爲了讓全部的數據都是immutable對象,則需引入redux-immutable
//安裝 yarn add redux-immutable
//使用
//項目主store中reducer.js修改
import { combineReducers } from'redux-immutable';
//組件中修改
const mapStateToProps = (state) => {
    return {
        list:state.getIn(['header','list']),
        focuse:state.getIn(['header','focuse']),
        // focuse:state.header.get('focuse'),
        // list:state.header.get('list')
    }
};
相關文章
相關標籤/搜索