reducer拆分与合并 - 图1

App.js

reducer拆分与合并 - 图2

index.js

importReactfrom‘react’; importReactDOMfrom‘react-dom’; importAppfrom‘./App’ import { createStore } from‘redux’ import totalReducer from ‘./Store/Reducer’ import { Provider } from‘react-redux’ const store = createStore(totalReducer) ReactDOM.render( <React.StrictMode> <Provider store={store}><App/></Provider> </React.StrictMode>, document.getElementById(‘root’) );

Person.reducer.js

import { ADDPERSON } from‘../Action_types/person.actions.types’ const initialState = [ { id:1, name:‘zoe’ } ] export default (state = initialState, action) => { switch (action.type) { case ADDPERSON: return [ state, action.payload ] default: return state } }

Reducer/index.js

import { combineReducers } from‘redux’ import counterReducerfrom‘./Counter.reducer’ import personReducerfrom‘./Person.reducer’ export default combineReducers({ //键值来自导包 counter:counterReducer, person:personReducer }) // {counter: {count}, person:[{}]}

person.actions.types.js

export const ADDPERSON = ‘addPerson’

Person.actions.js

import { ADDPERSON } from‘../Action_types/person.actions.types’ export const addPerson = (payload) => ({ type:ADDPERSON, payload })

Person.js

import React from‘react’ import { connect } from‘react-redux’ import { bindActionCreators } from‘redux’ import * as personActions from‘../Store/Actions/Person.actions’ function Person(props) { return ( <div> <button onClick={() => { props.addPerson({ id:2, name:“syy” }) }}>新增用户</button> <ul> { //键名访问 props.person.map(item=> { return<likey={item.id}>{item.name}</li> }) } </ul> </div> ) } const mapStateToProps = state=> ({ person: state.person }) const mapDispatchToProps = dispatch=> ({ bindActionCreators(personActions, dispatch) }) export default connect(mapStateToProps, mapDispatchToProps)(Person)