2013年 Facebook 提出了 Flux 架构的思想,引发了很多的实现。2015年,Redux 出现,将 Flux 与函数式编程结合一起,很短时间内就成为了最热门的前端架构。
简单说,如果你的UI层非常简单,没有很多互动,Redux 就是不必要的,用了反而增加复杂性。如果你的项目组件的数量和层级也变得越来越多,越来越深,此时组件间的数据通信就变得异常的复杂和低效,为了解决这个问题,引入了状态管理(redux)从而很好的解决多组件之间的通信问题。
安装Redux
redux不是内嵌在react框架中,使用时需要手动去安装
npm i -S redux
- 单一数据源
整个应用的 state 被储存在一棵对象结构中,并且这个对象结构只存在于唯一一个 store 中
不能直接去修改此数据源中的数据(数据深拷贝)
- State 是只读的
state redux中的state
唯一改变 state 的方法就是触发 action,action 是一个用于描述已发生事件的普通对象。
action只能是一个对象
- 使用纯函数(reducer)来执行修改
为了描述 action 如何改变 state tree ,你需要编写 reducer,reducer只是一些纯函数,它接收先前的 state 和 action,并返回新的 state
操作原理图
使用redux
创建统一数据源
store的index.js// 统一数据仓库
// * as 名称 as es6模块化导入起别名 // * 用export导出所有的方法或对象 // import * as redux from 'redux' // createStore 创建一个数据仓库 import { createStore } from 'redux' // 默认数据源不能直接修改 const defaultState = { count = 1 } // reducer纯函数 reducer中不修改state中的数据,只能返回新的state数据 (深拷贝) // 此参数是一个对象,是通过dispatch发送过来的,一般两个值 /* // action 动作对应的数据可以为任意数据类型 {type:'动作',payload:mixed} */ function reducers(state = defaultState, action) { if ('incr' === action.type) { // 返回新的state return { count: state.count + 1 } } return state } // 创建仓库 const store = createStore( reducers, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__() ) // 导出
export default store
在组件里面使用
import React, { Component } from 'react'
// 引入数据源
import store from './store'
export default class App extends Component {
constructor(props) {
super(props);
/* this.state = {
count:store.getState().count
} */
this.state = store.getState()
// 订阅
/* store.subscribe(()=>{
this.setState(state=>{
return {
count:store.getState().count
}
})
}) */
store.subscribe(() => {
// 如果有数据修改,则会自己更新状态数据
this.setState(state => store.getState())
})
}
render() {
return (
<div>
<h3>{this.state.count}</h3>
<button onClick={this.incr}>+++</button>
</div>
)
}
incr = () => {
// action creator必须是对象
const actionCreator = {
type: 'incr',
payload: 1
}
// 派发一个任务给reducer 给一个任务清单
store.dispatch(actionCreator)
}
}
右侧赞助一下 代码改变世界一块二块也是爱