比如在页面中添加和删除‘222’
action.js
export const ADD= 'ADD'; export const RED='RED'; export const add=(str)=>{ return{ type:'ADD', payload:str } }; export const red=(str)=>{ return { type:'RED', payload:str } };
reducer.js
import {combineReducers} from 'redux'; import {ADD,RED} from '../action'; const initialState = { cartData:["1","2","3"] }; const cartReducer=(state=initialState,action)=>{ state = JSON.parse(JSON.stringify(state));//深拷贝数据 switch (action.type){ case ADD: state.cartData.push('222'); return {cartData:state.cartData}; break; case RED: state.cartData.pop(); return {cartData:state.cartData} default: return state; } }; const reducer = combineReducers({ cartReducer }); export default reducer;
addStr.js
import React,{Component} from 'react' import { connect } from 'react-redux'; class AddStr extends Component{ constructor(props){ super(props) } render(){ const {cartData,addCartData}= this.props; const datas=this.state.datas; console.log(datas) return( <div className='adds'> <ul> { cartData.map((item,index)=>{ return <li key={index}>{item}</li> }) } </ul> <button onClick={()=>addCartData()}>添加字符</button> </div> ) } } function mapStateToProps(state) { return{ cartData:state.cartReducer.cartData } } function mapDispatchToProps(dispatch) { return{ addCartData:()=>dispatch({type:'ADD'}) } } export default connect( mapStateToProps, mapDispatchToProps )(AddStr);
redStr.js
import React, { Component } from 'react'; import { connect } from 'react-redux'; class RedStr extends Component{ constructor(props){ super(props); }; render(){ const {cartData,addCartData}= this.props; return ( <div> <button onClick={()=>addCartData()}>删除字符串</button> </div> ) } } function mapStateToProps(state) { console.log(state.cartReducer); return{ cartData:state.cartReducer.cartData } } function mapDispatchToProps(dispatch) { return{ addCartData:()=>dispatch({type:'RED'}) } } export default connect( mapStateToProps, mapDispatchToProps )(RedStr);
roots.js
import React, { Component } from 'react'; import AddStr from '../components/addStr' import RedStr from '../components/redStr' class Roots extends Component{ constructor(props){ super(props); } render(){ return ( <div> <AddStr/> <RedStr /> </div> ) } } export default Roots;