Redux初级

安装antd

npm install antd --save

安装redux

npm install --save redux

使用redux进行统一的数据源管理
component -> action -> store -> reducer
reducer 存储数据,返回给store,action从store获取数据

//####TodoList.js
import store from './store/index'
...
    constructor(props){
        super(props)
        this.state = store.getState()
    }
...
//调用的地方
 dataSource={this.state.list}
...
//####store/index.js
import reducer from './reducer'
const store = createStore(reducer)
export default store
//####reducer.js
const defaultState = {
    inputValue : 'xxxxoooo'
}
export default (state = defaultState, action) => {
    return state
}

Chrome 工具

//####Redux Dev Tools
const store = createStore(
    reducer,
    window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
) // 创建数据存储仓库

修改数据
构造函数订阅(subscribe)数据变化,每个动作触发(dispatch)store变化,reducer 返回newState,不能直接修改state

//####TodoList.js
constructor(props) {
    super(props)
    this.state = store.getState()
    this.clickBtn = this.clickBtn.bind(this)

    this.storeChange = this.storeChange.bind(this)
    store.subscribe(this.storeChange)
}
...
storeChange() {
    this.setState(store.getState())
}
...
clickBtn() {
    const action = {
        type: 'addItem'
    }
    store.dispatch(action)
}
//####reducer.js
const defaultState = {
    inputValue : 'input a value',
    list: []
}
export default (state = defaultState, action) => {
    if (action.type === 'addItem') {
        let newState = JSON.parse(JSON.stringify(state))
        newState.list.push(newState.inputValue)
        newState.inputValue = ''
        return newState
    }
    return state
}

整理actionType,写到一个文件里面,统一管理, reducer 和 ToDoList 需要统一

export const  CHANGE_INPUT = 'changeInput'
export const  ADD_ITEM = 'addItem'
export const  DELETE_ITEM = 'deleteItem'

把action 抽象出来放在一个统一的文件中管理

//####TodoList.js
import { changeInputAction, addItemAction, deleteItemAction} from './store/actionCreators'
...
changeInputValue(e) {
    const action = changeInputAction(e.target.value)
    store.dispatch(action)
}
//####actionCreators.js
import {CHANGE_INPUT, ADD_ITEM, DELETE_ITEM}  from './actionTypes'
export const changeInputAction = (value) => ({
    type : CHANGE_INPUT,
    value
})

你可能感兴趣的:(Redux初级)