Redux的工作流程图
Store为公共数据的存储库。当组件需要更新Store中的数据时,需要分发一个Action告知Store,Store中没有逻辑,需要通过Reducer处理Action,经过Reducer处理过后返回新的状态,Store获取更新后的状态后Store更新,这时候组件需要订阅Storestore.subscribe()
,当Store变更时会调用subscribe()
,这时组件设置更新statethis.setState(store.getState())
,实现store即视图实时更新的效果。
创建一个Store
存储数据的公共区域
//store.js
import { createStore } from 'redux'
import reducer from './reducer'
const store = createStore({
reducer
})
创建一个Reducer
纯函数是指给定固定的输入则会有固定的输出且不会有任何副作用
即不可以使用类似日期或异步等会使结果发生变化的动作
//reducer.js
//设置Store的初始状态
const defaultStore = {
inputValue: '',
list: []
}
//Reducer必须是一个纯函数
export default (state = defaultStore, action) => {
if (action.type === ADD_TODO_ITEM) {
const newState = JSON.parse(JSON.stringify(state))
newState.list.push(newState.inputValue)
newState.inputValue = ''
return newState
}
return state
}
ActionCreator
通常在项目中,action会通过函数来创建,这便于我们后续测试
//actionCreatore.js
import {
//引入定义好的常量
CHANGE_INPUT_VALUE,
ADD_TODO_ITEM
...
} from "./actionTypes";
export const getInputChangeAction = value => ({
type: CHANGE_INPUT_VALUE,
value
})
export const getAddTodoItemAction = () => ({
type: ADD_TODO_ITEM
})
...
//actionTypes.js
export const CHANGE_INPUT_VALUE = 'change_input_value'
export const ADD_TODO_ITEM = 'add_todo_item'
...
创建一个Component
//TodoList.js
import React, { Component } from 'react'
import {
getAddTodoItemAction
...
} from './store/actionCreator'
class TodoList extends Component {
constructor(props) {
super(props)
this.state = store.getState()
this.handleAddTodoItem.bind(this)
...
this.handleStoreChange = this.handleStoreChange.bind(this)
store.subscribe(this.handleStoreChange) //订阅store,当store发生变化时subscribe会被调用
}
handleAddTodoItem() {
const action = getAddTodoItemAction()
store.dispatch(action)
}
...
//处理store变化
handleStoreChange() {
this.setState(store.getState()) //当store变更时重新设置state
}
}
export default TodoList
0