注意
state不可变,Reducer每次都返回新的state。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| const state = { user: 'CamperBot', status: 'offline', friends: '732,982', community: 'freeCodeCamp' };
Object.assign({},state,{status:'online'});
const state2 = [1,2,3,4,5,6]; return state2.slice(0, action.index).concat(state2.slice(action.index + 1, state2.length));
return [ ...state.slice(0, action.index), ...state.slice(action.index + 1, state.length) ];
|
监听store的更新
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| function test(){ console.log('每次调用store.dispatch时都会跑‘); } store.subscribe(test); ``` ## 基本使用 ```javascript
//定义一种type const ADD_NOTE = 'ADD_NOTE';
//reducer const notesReducer = (state = [], action) => { switch(action.type) { //处理一种type case ADD_NOTE: //state不可变。如果state为list,需要使用[...state]拷贝一份。 return [...state,{ message : action.text, }]; default: return state; } };
//返回一个action,包含type,和一些数据 const addNoteText = (note) => { return { type: ADD_NOTE, text: note }; };
//创建store const store = Redux.createStore(notesReducer);
//用dispatch发送包含数据的action,修改数据 store.dispatch(addNoteText('一串文本'));
|
拆分state
可以将 state 分成多个块。
定义多个reducer来处理。使用combineReducers组合成一个root reducer。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| const rootReducer = Redux.combineReducers({ auth: authenticationReducer, notes: notesReducer });
```
## ReduxThunk异步操作 ```javascript
const REQUESTING_DATA = 'REQUESTING_DATA' const RECEIVED_DATA = 'RECEIVED_DATA'
const requestingData = () => { return {type: REQUESTING_DATA} } const receivedData = (data) => { return {type: RECEIVED_DATA, users: data.users} }
const handleAsync = () => { return function(dispatch) { store.dispatch(requestingData()); setTimeout(function() { let data = { users: ['Jeff', 'William', 'Alice'] } store.dispatch(receivedData(data)); }, 2500); } };
const defaultState = { fetching: false, users: [] };
const asyncDataReducer = (state = defaultState, action) => { switch(action.type) { case REQUESTING_DATA: return { fetching: true, users: [] } case RECEIVED_DATA: return { fetching: false, users: action.users } default: return state; } };
const store = Redux.createStore( asyncDataReducer, Redux.applyMiddleware(ReduxThunk.default) );
|