组成三要素
- State(Store)
- Action
- Reducer

简述
在Redux中,所有对Store的修改都通过一个Reducer去完成,而不是直接修改Store。
- 保证数据不可变性(Immutable)
- 可预测性(Predictable):即 给定初始状态和action,能得到一致的结果
- 易于调试:Redux浏览器插件
import { createStore } from 'redux'
// State初始值
const initialState = { value: 1 }
// Reducer
const countReducer = (state = initialState, action) => {
swith(action.type) {
case 'increamentd':
return { value: state.value + 1 }
case 'decreamentd':
return { value: state.value - 1 }
default:
return state
}
}
// 创建store
export const store = createStore(countReducer)
// Store提供了subscribe,用于监听变化
store.subscribe(()=>{
// Store提供了getState()方法,用于获取state
console.log(store.getState())
})
// Store提供了dispatch方法,用于分发一个Action,触发Reducer去更新state
const increamentAction = { type: 'increamented' }
store.dispatch(inscreamentAction)
// 监听到输出 { value: 2 }Redux只是提供了数据流动部分,UI渲染上需要和React配合,所以有react-redux这个库