redux的使用(三)--combineReducers

2020-11-18  本文已影响0人  龙猫六六

combineReducers

使用combineReducers解决的目的:

使用说明

步骤一 定义子reducer.js

student_reducer.js文件,export handleActions对象

// reducer/student_reducer.js
import {handleActions} from "redux-actions";
import actionType from "../actionType";

const defaultState = {
    students:[{name:'默认',age:0}]
}

export const students = handleActions({
    [actionType.GET_STUDENT_LIST]:(state, action)=>{
        const students = [{name:'张同学',age:19},{name:'李同学',age:19},{name:'王同学',age:19}]
        return {...state, students:students
        }
    },
    [actionType.ADD_STUDENT_LIST]:(state, action)=>{
        return {...state, students: [...state.students, action.payload]
        }
    }
},defaultState)

teacher_reducer.js文件,export handleActions对象

// reducer/teacher_reducer.js
import actionType from "../actionType";
import {handleActions} from "redux-actions";
const defaultState = {
    teachers:[{name:'默认', age:0}]
}
export const teachers = handleActions({
    [actionType.GET_TEACHER_LIST]:(state, action)=>{
        const teachers = [
            {name:'张老师',age:32},
            {name:'李老师',age:42},
        ]

        return {
            ...state,
            teachers:teachers,
        }
    },
    [actionType.ADD_TEACHER_LIST]:(state, action)=>{
        return {
            ...state,
            teachers: [...state.teachers, action.payload]
        }
    },
}, defaultState)

步骤二 定义出口reducer.js

// reducer/index.js
import {combineReducers} from 'redux'
import {students} from "./student_reducer";
import {teachers} from "./teacher_reducer"

export const reducer =  combineReducers({
    students,//同名的写法,也可以写成key:value键值对的形式,如下
    teachers:teachers,
})

基本使用方法是:

步骤三 store的引用

//store.js
import {createStore, applyMiddleware,compose} from 'redux'
import {reducer} from "./reducer/index"

const store = createStore(reducer)
export default store

步骤四 组件中的使用

采用react-reducx定义sotre的state赋值给props,因此关注mapStateToProps中的定义

const mapStateToProps = (state) => {
    return {
        students: state.students.students,
        teachers: state.teachers.teachers,
    }
}

export default connect(mapStateToProps, {
    getStudentList: studentActions.getStudentList,
    addStudent: studentActions.addStudentList,

    getTeacherList1: teacherActions.getTeacherList,
    addTeacherList1: teacherActions.addTeacherList,
})(App)
reducer/index.js
export const reducer =  combineReducers({
    students,//同名的写法,也可以写成key:value键值对的形式,如下
    teachers:teachers,
})
  1. 以key和value的值进行关联
{
    getStudentList: studentActions.getStudentList,
    addStudent: studentActions.addStudentList,

    getTeacherList1: teacherActions.getTeacherList,
    addTeacherList1: teacherActions.addTeacherList,
}


getStudentList为组件中props的行为定义
studentActions.getStudentList为studentActions具体定义的行为

上一篇下一篇

猜你喜欢

热点阅读