redux

Posted by アライさん on 2022年09月13日

注意

state不可变,Reducer每次都返回新的state。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//用state生成一个新的object,将其中的status替代为'online'。
const state = {
user: 'CamperBot',
status: 'offline',
friends: '732,982',
community: 'freeCodeCamp'
};
//Object.assign将state复制到{}中,再替代其中的{status:'online'}
Object.assign({},state,{status:'online'});


//state为list,删除中间一项,使用concat或者...生成新的list
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

//定义一些type
const REQUESTING_DATA = 'REQUESTING_DATA'
const RECEIVED_DATA = 'RECEIVED_DATA'

//定义发送请求的action和收到请求的action
const requestingData = () => { return {type: REQUESTING_DATA} }
const receivedData = (data) => { return {type: RECEIVED_DATA, users: data.users} }


const handleAsync = () => {
return function(dispatch) {
// 在这里发送 request action
store.dispatch(requestingData());
setTimeout(function() {
let data = {
users: ['Jeff', 'William', 'Alice']
}
// 在这里发送接收到的 data action
store.dispatch(receivedData(data));
}, 2500);
}
};

//定义默认的state
const defaultState = {
fetching: false,
users: []
};

//reducer
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;
}
};

//使用applyMiddleware和ReduxThunk创建异步操作
const store = Redux.createStore(
asyncDataReducer,
Redux.applyMiddleware(ReduxThunk.default)
);