1. 程式人生 > >Redux 基本步驟小結:

Redux 基本步驟小結:

Redux 基本步驟小結:

1.建立reducer.js

直接匯出函式,(state=defaultState,action)=>{… return state;}
先初始化dafaultState
函式體內根據action.type對資料執行不同的操作
(用const newState = JSON.parse(JSON.stringify(state));**對state進行深拷貝)

const defaultState={
	inputValue:'',
	list:[]
}

export default (state=defaultState,action)=>{
	if(action.type === "change_input_value"){
		const newState=JSON.parse(JSON.stringify(state));
		newState.inputValue=action.value;
		return newState;
	}
	retunrn state;
}

2.建立store

採用從redux中匯入的createStore()方法建立
第一個引數為從reducer中匯入的reducer,第二個引數為瀏覽器調Redux外掛語句

import { createStore } from 'redux';
import reducer from './reducer';

const store = createStore(reducer,
	 window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());


export default store;

3.在component中引入資料

import store from ‘xxx’
用this.state=store.getState()得到資料
在建構函式中加入store的訂閱( subscribe() ),讓每次資料變化都會自動呼叫render進行渲染

constructor(props) {
        super(props);
        this.state = store.getState();
        store.subscribe(()=>{this.setState(store.getState())});
    }

4.建立actionTypes.js

明晰要採用的action,將其放在這個檔案已變數形式進行輸出,統一管理,方便進行debug和測試

export const change_input_value="change_input_value";
export const add_item="add_item";
...

5.建立actionCreateors.js

從actionTypes中引入各個action變數
以函式形式匯出各個action函式

import { change_input_value , add_item} from './actionTypes.js';

export const inputChangeAction=(value)=>({
	type: change_input_value,
	value:value
});

export const addItemAction=()=>({
	type: add_item
});

6.component完善

接收actionCreareors中的各個action
賦值給action
傳送action到store( store.dispatch(action) )

...
inputText(e){
    	const value=e.target.value;
    	const action=inputChangeAction(value);
    	store.dispatch(action);
    }
...