1.安裝redux及基礎(chǔ)文件的創(chuàng)建
1.終端安裝yarn add redux
2在src 目錄下新建store文件夾,在store中創(chuàng)建index.js文件
3在index.js中導(dǎo)入 import {createStore} from 'redux;
4 創(chuàng)建數(shù)據(jù)公共存儲倉庫 const store = createStore();
5.導(dǎo)出store ?export default store
6.創(chuàng)建reducer.js文件
7.定義默認(rèn)的數(shù)據(jù) const defaultState = {inputValue:'123', list:[1,2]}
8.導(dǎo)出一個方法 export default (state = defaultState, action) =>{return state;}
9.在index.js中導(dǎo)入reducer.js。import reducer from './reducer',把store.js中創(chuàng)建store修改為const store = createStore(reducer)
10.在需要使用數(shù)據(jù)的組件中導(dǎo)入store。import store from './store/index.js'或者import store from './store'
11.通過store.getState()獲取數(shù)據(jù)
2.組件通過redux修改數(shù)據(jù)
1.創(chuàng)建action對象
const action = {
? ? ? type:'input_value_change',
? ? ? value:e.target.value
}
2.通過store把action對象傳給reducer.js。store.dispatch(action);
3.在reducer.js中導(dǎo)出的(state = defaultState, action) =>{}方法中修改store中的state,在方法中返回新的state完成,在方法中不能修改原來的state,需要復(fù)制一份state
const newState = JSON.parse(JSON.stringify(state))
復(fù)制修改數(shù)據(jù)后返回newState.
4.在組件中通過store.subscribe(this.handleStateChange)監(jiān)聽state的改變。然后在this.handleStateChange中重新給state賦值,重新調(diào)用render方法
3.調(diào)試redux需要安裝插件redux devtools
1.在谷歌插件商城下載安裝 redux-devtools
2.在store文件夾下的index.js中配置
const store = createStore(reducer,
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());
4.創(chuàng)建actionTypes.js文件,統(tǒng)一保存action的type
導(dǎo)出方式
export const KEY = 'value';
導(dǎo)入方式,import { KEY?} from './store.actionTypes'
5.統(tǒng)一管理action
創(chuàng)建actionCreators.js文件
導(dǎo)出方法。例如
export const getInputChangeAction = (value) => ({
????type:KEY,
????value
});
該方法傳入value,返回action對象,當(dāng)使用redux-thunk中間件之后可以返回函數(shù)
6.給不同模塊創(chuàng)建不同的reducer.js文件,通過combineReducers進行整合
在最外面的store中導(dǎo)入combineReducers
import {combineReducers} from 'redux;
假設(shè)headerReducer是一個模塊的reducers,在導(dǎo)入 headerReducer后,整合方式如下
const reducer = combineReducers({
? ? header:headerReducer
});
export default reducer;
其中header是headerReducer的名稱。
注意:此時在做印社關(guān)系時,headerReducer中的數(shù)據(jù)需要通過state.headerReducer.屬性得到
當(dāng)模塊中的state為不可變對象時,合并出的state也改成不可變對象的方法
1.終端導(dǎo)入redux-immutable。 yarn add redux-immutable。
2.在文件中導(dǎo)入
import {combineReducers} from 'redux-immutable'
3.生成不可變對象
const reducer = combineReducers({
????header:headerReducer
});
此時獲取屬性需要使用state.get('header').get('key')
或者state.getIn(['header', 'focused'])
7.導(dǎo)入immutable,使reducer中傳入的state不可變
1.導(dǎo)入:yarn add immutable
2.在reducer中導(dǎo)入fromJS
import {fromJS} from 'immutable;
3.創(chuàng)建immutable對象
const defaultState = fromJS({
? ? test:false
});
4.immutable對象獲取屬性值
state.getIn('test')
5.immutable對象設(shè)置屬性值
state.set('test', true);
immutable的set方法,會結(jié)合之前immutable對象的值和新設(shè)置的值生成一個新的immutable對象
在用immutable對象時必須使用getIn、set操作屬性值,因為普通對象沒有這兩個方法
immutable對象可以使用merge修改值,參數(shù)傳一個對象