Redux

作者: 灯光树影 | 来源:发表于2018-09-25 09:31 被阅读0次

    一、什么是Redux

    Redux是一个数据层的框架,React可以借助Redux来实现数据的传递
    Redux等于Reducer加上Flux

    二、Redux的示意图

    redux.png

    三、Redux的工作流程

    reduxFlow.png

    每次组件更新的时候,到发送命令给store,然后store从reducers中获取新数据,然后返回给组件

    四、代码编写

    • 创建store
    import {createStore} from 'redux';
    import reducer from './reducer';
    
    // 第二个参数使用redux-devtools-extension插件
    const store = createStore(reducer, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());
    
    export default store;
    
    • 编写actionTypes
    export const CHNAGE_INPUT_VALUE = 'change_input_value'
    export const ADD_TODO_ITEM = 'add_todo_item'
    export const DELETE_TODO_ITEM = 'delete_todo_item'
    
    • 编写actionCreator
    import {CHNAGE_INPUT_VALUE, ADD_TODO_ITEM, DELETE_TODO_ITEM} from './actionTypes' 
    
    export const getChangeInputValueAction = (value) => ({
        type: CHNAGE_INPUT_VALUE,
        value
    })
    
    export const getAddTodoItemAction = () => ({
        type: ADD_TODO_ITEM
    })
    
    export const getDeleteTodoItemAction = (index) => ({
        type: DELETE_TODO_ITEM,
        index
    })
    
    • 编写reducer
    import {CHNAGE_INPUT_VALUE, ADD_TODO_ITEM, DELETE_TODO_ITEM} from './actionTypes' 
    
    // 默认数据
    const defaultState = {
        inputValue: '',
        list: [1, 2]
    }
    
    export default (state = defaultState, action) => {
        let newState = JSON.parse(JSON.stringify(state))
        if(action.type === CHNAGE_INPUT_VALUE){
            newState.inputValue = action.value
            return newState
        }
        if(action.type === ADD_TODO_ITEM){
            newState.list.push(newState.inputValue)
            newState.inputValue = ''
            return newState 
        }
        if(action.type === DELETE_TODO_ITEM){
            newState.list.splice(action.index, 1)
            return newState
        }
        return state
    }
    
    • 使用state
    this.state = store.getState() // 获取store
    store.subscribe(this.handleStoreChange) // 自动订阅,如果store改变,组件自动调用handleStoreChange
    handleStoreChange(){
        this.setState(store.getState())
    }
    // 发送action
    const action = getAddTodoItemAction()
    store.dispatch(action)
    
    • 代码的流程图
      redux-code.jpg

    相关文章

      网友评论

          本文标题:Redux

          本文链接:https://www.haomeiwen.com/subject/xfdqoftx.html