redux筆記
action: 一個操作的定義,大概是這個樣子, 本身是一個對象
{
type:'add',
todo
}
actionCreater: 一個函數,返回結果是一個action
function add (todo) {
return {
type: 'add',
todo
}
}
reducer: 真正更新數據操作的函數,大概是這麼個樣子
==此處return狀態不可以直接改,可以用解構,對象還可以Object.assign()==
// reducer
let todoReducer = function (state = todoList, action) {
switch (action.type) {
case 'add':
return [...state, action.todo]
case 'delete':
return state.filter(todo => todo.id !== action.id)
default:
return state
}
}
store: 只有一個,把action,state,reducer連接起來的對象。有如下方法
dispatch:觸發一個action
subscribe : 訂閱store
getState :獲得當前的state
replaceReducer :更換reducer
/* 簡單示例 */
let { createStore } = self.Redux
//默認state
let todoList = []
// reducer
let todoReducer = function (state = todoList, action) {
switch (action.type) {
case 'add':
return [...state, action.todo]
case 'delete':
return state.filter(todo => todo.id !== action.id)
default:
return state
}
}
//創建store
let store = createStore(todoReducer)
//訂閱
function subscribe1Fn() {
console.log(store.getState())
}
let sub = store.subscribe(subscribe1Fn)
store.dispatch({
type: 'add',
todo: {
id: 1,
content: '學習redux'
}
})
store.dispatch({
type: 'add',
todo: {
id: 2,
content: '吃飯睡覺'
}
})
store.dispatch({
type: 'delete',
id: 2
})
// 取消訂閱
sub()
console.log('取消訂閱後:')
store.dispatch({
type: 'add',
todo: {
id: 3,
content: '打遊戲'
}
})
運行結果: