上一篇文章中提到,Redux是为了解决在复杂的应用中状态管理的工具。那么,该如何使用Redux呢?
Redux的使用
根据Redux的三大原则——全局唯一性、只读性、纯函数(修改)性,我们首先来看看Redux的组成
Redux的组成
- Store
既然是管理状态的工具,那么必须要有一个存储状态的地方,这个称为Store - Reducer
既然状态是只读的,必须要提供更新的接口,这个称为Reducer - Action
Reducer只是提供了怎么去更新状态的接口,那什么时候调用Reducer呢——向Store发一个Action。Action中指定了要调用的Reducer以及需要用来更新状态的数据
除了作为一个状态管理中心所必备的功能之外,Redux还有以下特征:
- 作为一个观察者模式中的被观察对象
实际上,观察者模式在这里被称为发布——订阅模式,即对状态感兴趣的页面,主动发出订阅请求,成为一个监听器。当状态中心里状态发生变化的时候,就会通知订阅者,执行监听器,相关的页面就会响应状态的变化。因此,Redux提供了一个订阅方法,并且维护了一个监听器列表。
如何集成Redux
Redux本身是作为一个状态管理工具,并不是和React绑定的。而React-Redux就是一个把React和Redux绑定的工具。使用React-Redux只是因为它可以帮助我们更好地在React中使用Redux,所以这里我们先考虑不使用中间件React-Redux的情况下,如何在React应用中使用Redux。
通过对Redux的剖析,我们大致也能归纳出使用Redux的步骤:
- 分析应用中的状态是什么,即确定Store中的数据
- 状态有哪些变化,以及如何变,即确定Reducer和Action
- 创建一个状态中心,即Store
- 在页面上订阅Store,即注册监听器
- 获取Store中的数据,并渲染UI
talk is cheap, show me the code.
说明如下:
这是一个todo应用,每一条todo都有三个状态:新增、完成、垃圾箱
-
创建了一个store,并添加了一个reducer,根据不同的status来更新状态
// store.js 这里为了方便,将整个Store及reducer、action都放在了一个文件
import { createStore } from 'redux'
const initialState = {
index: 0,
todoList: [],
}
export default createStore((state = initialState, { type, payload = {} }) => {
const { index, status } = payload
switch(type) {
case 'NEW':
{
payload.key = state.index
payload.status = 'UNDONE'
return {
todoList: [
...state.todoList,
payload
],
index: state.index + 1
}
}
case 'DONE':
return {
todoList: state.todoList.map((todo, i) => {
i === index ? todo.status = 'DONE' : todo
return todo
}),
index: state.index
}
case 'UNDONE':
return{
todoList: state.todoList.map((todo, i) => {
i === index ? todo.status = 'UNDONE' : todo
return todo
}),
index: state.index
}
case 'TRASH':
return{
todoList: state.todoList.map((todo, i) => {
i === index ? todo.status = 'TRASH' : todo
return todo
}),
index: state.index
}
case 'RETRIVE':
return{
todoList: state.todoList.map((todo, i) => {
i === index ? todo.status = 'UNDONE' : todo
return todo
}),
index: state.index
}
default:
return state
}
})
这里创建了一个高阶组件,其中导入了Redux中的store,并在componentDidMount
和componentWillUnmount
订阅并且退订了store。
import React from 'react'
import store from '../models/store'
export const wrap = (WrappedComponent) => {
return class extends React.Component {
constructor(props) {
super(props)
this.state = {
data: store.getState(),
}
this.dispatch = store.dispatch
}
componentDidMount() {
this.unsubscribe = store.subscribe(() => this.setState({
data: store.getState()
}))
}
componentWillUnmount() {
this.unsubscribe()
}
render() {
const { data } = this.state;
return (
<WrappedComponent {...this.props} dispatch={this.dispatch} data={data} />
)
}
}
}
这里是Home页面,通过utils.wrap(Home)来包装,获得了dispatch方法,通过dispatch能够向store发送更新状态的Action,从而完成对用户操作的响应
import React from 'react';
import ToDoList from '../../components/ToDoList/todolist'
import * as utils from '../../utils'
class Home extends React.Component {
constructor(props) {
super(props)
}
submit = (e) => {
e.preventDefault()
const { dispatch } = this.props
dispatch({
type: 'NEW',
payload: {
content: this.addToDo.value
}
})
this.addToDo.value = ''
}
onDone = todo => {
const { dispatch } = this.props
dispatch({
type: 'DONE',
payload: {
index: todo.key
}
})
}
onTrash = todo => {
const { dispatch } = this.props
dispatch({
type: 'TRASH',
payload: {
index: todo.key
}
})
}
render() {
const { data: { todoList } } = this.props
return (
<div>
<form>
<input name="todo" ref={ref => this.addToDo = ref} />
<button type="submit" onClick={this.submit}>add</button>
</form>
<h2>新的TODOS</h2>
<ToDoList
onChange={this.onDone}
onRemove={this.onTrash}
todoList={todoList.filter(todo => todo.status === 'UNDONE')}
></ToDoList>
</div>
)
}
}
export default utils.wrap(Home)