redux 实践总结

View 层:React
状态管理:Redux,管理数据状态和UI状态的JavaScript应用工具

Redux工作流.png

举例说明:


image.png

代码实践:
主文件

import React, { Component } from 'react';
import 'antd/dist/antd.css'
import {Input,Button,List} from 'antd'
import store from './store'
import {changeInputAction,addItem,deleteItem} from './store/actionCreators'

//最开始写死了列表组件的内容,后来通过redux createStore(reducer) 里面设置了data这里就不用了
//const data=['one','two','three']

class TodoList extends Component {
    constructor(props){
        super(props)
        this.storeChange = this.storeChange.bind(this)
        this.state=store.getState()
        this.changeInputValue = this.changeInputValue.bind(this)
        this.addList=this.addList.bind(this)
        this.deleteItem=this.deleteItem.bind(this)
        // 订阅状态变化,只要发生变化调用storeChange,获取最新state赋值给state
        store.subscribe(this.storeChange)
        
    }
    
    render() { 
        return ( 
            
({item})} />
); } //input标签内的onChange属性绑定changeInputValue;输入框内容变化则传参e给changeInputValue changeInputValue(e){ // const action = { // // action type区分一个动作的类型 // type:CHANGE_INPUT, // value:e.target.value // } const action=changeInputAction(e.target.value) //changeInputValue调用store派遣action方法,action创建了值,把值传给store store接收 自动传给reducers去调度 store.dispatch(action) } addList(){ // const action = {type:ADD_ITEM} const action = addItem() store.dispatch(action) } deleteItem(index){ // const action={type:DELETE_ITEM,index} const action=deleteItem(index) store.dispatch(action) } storeChange(){ this.setState(store.getState) } } export default TodoList;

store/index.js

import {createStore} from 'redux';
import reducer from './reducer';

const store = createStore(reducer,
    window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
    )
export default store

store/reducer.js

import {CHANGE_INPUT,ADD_ITEM,DELETE_ITEM} from './actionTypes'


const defaultState = {
    inputValue:'please input',
    list:['one','two','three']
}

export default (state = defaultState,action)=>{

    console.log(state,action)
    //Reducer里只接收state不能直接改变state,可以用中间变量来改变
    if(action.type===CHANGE_INPUT){
        //JSON.parse(JSON.stringify()) ES6深度拷贝
        let newState = JSON.parse(JSON.stringify(state))
        newState.inputValue=action.value
        return newState

    }
    if(action.type===ADD_ITEM){
        //JSON.parse(JSON.stringify()) ES6深度拷贝
        let newState = JSON.parse(JSON.stringify(state))
        newState.list.push(newState.inputValue)
        newState.inputValue=''
        return newState

    }

    if(action.type===DELETE_ITEM){
        //JSON.parse(JSON.stringify()) ES6深度拷贝
        let newState = JSON.parse(JSON.stringify(state))
        newState.list.splice(action.index,1)
        
        return newState

    }
    
    return state
}

你可能感兴趣的:(redux 实践总结)