flux是个数据层框架,因为flux数据都存储在store中,所以推出了redux
yarn add redux
redux提供的创建store方法:
import { createStore } from ‘redux‘
import reducer from ‘./reducer‘
const store = createStore(reducer)
export default store
redux的核心API
createStore(生成store)
const store = createStore(reducer, { inputValue: ‘‘, list: [] })
store.dispatch(触发state改变的唯一途径)
store.dispatch(action) //把action发送到store中
store.getState(获取整个state树)
this.state = store.getState() //取得当前时刻的state
store.subscribe(监听)redux自动发布,只需监听
store.subscribe(this.handleStoreChange.bind(this))
unsubscribe(取消监听)
const unsubscribe = store.subscribe(this.handleStoreChange.bind(this)) unsubscribe()
Redux三大原则
- redux和store建议只有一个
- 只有store自己可以改变自己
- reducer是一个纯函数(给入固定的输入一定会有固定的输出,禁止使用ajax,时间戳)
reaux与flux的差异
Redux没有分发器Dispatcher,增加了Reducers