Redux概念
Redux = Reducer + Flux,数据层框架,将所有数据都存储到store中
Redux的工作流程
Antd的使用
安装:npm install antd --save
import 'antd/dist/antd.css'
import { Input, Button, List } from 'antd'
<div style={{ margin: '10px 0 0 10px' }}>
<Input style={{ width: '300px' }} />
<Button type="primary">提交</Button>
<List
bordered
dataSource={this.state.list}
renderItem={item => (<List.Item>{item}</List.Item>)}
style={{ width: '363.84px', marginTop: '5px' }}
/>
</div>
redux的使用
安装:npm install redux --save
1、创建store目录,并在此目录下创建index.js文件
import { createStore } from 'redux'
import reducer from './reducer'
const store = createStore(reducer)
export default store
2、创建reducer.js
const defaultState = {
inputValue: '123',
list: ['a', 'b']
}
export default (state = defaultState, action) => {
return state
} //reducer可以接收state,但绝不能修改state
3、使用store
import store from './store'
console.log(store.getState())
action和reducer
1、组件派发action
handleInputChange(e) {
const action = {
type: 'change_input_value',
value: e.target.value
}
store.dispatch(action)
} //store接收到action,将当前状态和action发送给reducer(内部自动触发)
//reducer是一个纯函数,给固定的输入就一定会有固定的输出(Date()就不行),而且不会有任何副作用(即不能改变参数的值)
2、reducer接收action,返回新状态
if (action.type === 'change_input_value') {
const newState = JSON.parse(JSON.stringify(state))
newState.inputValue = action.value
return newState
} //store接收到返回的新状态,更新state(内部触发)
3、组件订阅store,当store中的数据更新时,实现同步更新
this.handleStoreChange = this.handleStoreChange.bind(this)
store.subscribe(this.handleStoreChange)
handleStoreChange() {
this.setState(store.getState())
}
使用ActionTypes统一管理action的type属性值
如果action的type属性值直接使用字符串,派发action的组件中和reducer中的值
都是以字符串给出的,若误写的不一致程序不会报错,bug难以排查。故使用常量,增强可维护性
//在store文件夹下创建actionTypes.js文件
export const CHANGE_INPUT_VALUE = 'change_input_value'
export const ADD_TODO_ITEM = 'add_todo_item'
export const DEL_TODO_ITEM = 'del_todo_item'
//在组件或reducer中使用
import { CHANGE_INPUT_VALUE, ADD_TODO_ITEM, DEL_TODO_ITEM } from './actionTypes'
使用actionCreators统一创建action
让组件的代码更简洁,也方便测试和后期维护
//在store文件夹中创建actionCreators.js文件
import { CHANGE_INPUT_VALUE, ADD_TODO_ITEM, DEL_TODO_ITEM } from './actionTypes'
export const getInputChangeAction = (value) => ({
type: CHANGE_INPUT_VALUE,
value
})
export const getAddItemAction = () => ({
type: ADD_TODO_ITEM
})
export const getDelItemAction = (index) => ({
type: DEL_TODO_ITEM,
index
})
//在组件中使用
import { getInputChangeAction, getAddItemAction, getDelItemAction } from './store/actionCreators'
const action = getInputChangeAction(e.target.value)