redux
//action.jsimport {INCREMENT,DECREMENT} from "./constant"export const createIncrement=data=>({type:INCREMENT,data})export const createDecrement=data=>({type:DECREMENT,data})
//constant.jsexport const INCREMENT='increment'export const DECREMENT='decrement'
//reducer.jsimport {INCREMENT,DECREMENT} from "./constant"const defaultState={ counter:0}export default function countReducers(preState = defaultState, action) { //从action中拿到type与data const { type, data } = action; //根据type加工数据 switch (type) { case INCREMENT: return {...preState,counter:preState.counter+data} case DECREMENT: return {...preState,counter:preState.counter-data} default: return preState; }}
//store.jsimport {createStore} from 'redux'import countReducer from "./reducer.js"import {composeWithDevTools} from 'redux-devtools-extension'console.log( countReducer );export default createStore(countReducer,composeWithDevTools())
使用
//about.jsximport React, { PureComponent } from 'react'import store from "../../redux/store"import {createDecrement} from "../../redux/action"export default class index extends PureComponent { state={ counter:store.getState().counter } componentDidMount(){ store.subscribe((()=>{ this.setState({ counter:store.getState().counter }) })) } decrementClick (){ store.dispatch(createDecrement(1)) } fivedecrementClick (num,e){ store.dispatch(createDecrement(num)) } render() { const {counter}=this.state return ( <div> <h1>减法区域</h1> <h2>当前计数为:{counter}</h2> <button onClick={c=>this.decrementClick()}>-1</button> <button onClick={c=>this.fivedecrementClick(5,c)}>-5</button> </div> ) }}
//home.jsximport React, { PureComponent } from 'react'import store from "../../redux/store"import {createIncrement} from "../../redux/action"export default class index extends PureComponent { state={ counter:store.getState().counter } componentDidMount(){ store.subscribe((()=>{ this.setState({ counter:store.getState().counter }) }))} firstClick=()=>{ store.dispatch( createIncrement(1)) } fiveClick=()=>{ store.dispatch( createIncrement(5)) } render() { const {counter}=this.state return ( <div> <h1>加法区域</h1> <h2>当前计数为:{counter}</h2> <button onClick={this.firstClick}>+1</button> <button onClick={this.fiveClick}>+5</button> </div> ) }}