//constants.js
// 定义常量
export const ADD_COUNT = 'ADD_COUNT';
export const SUB_COUNT = 'SUB_COUNT';
export const APPEND = 'APPEND';
export const REMOVE = 'REMOVE';
//action.js
import {
ADD_COUNT,
SUB_COUNT,
APPEND,
REMOVE
} from './constants';
// 利用action来修改状态
export const addAction = (num)=>{
return {type:ADD_COUNT, num: num};
};
export const subAction = (num)=>{
return {type:SUB_COUNT, num: num};
};
export const append = ()=>{
return {type:APPEND};
};
export const remove = ()=>{
return {type:REMOVE};
//personReducer.js
import {APPEND,REMOVE} from './constants'
// 1.定义一个状态(数据)
let initialState = {
name: 'Tom'
}
// 利用reducer将store和action串联起来
function personReducer(state = initialState, action){
console.log(state,action)
switch(action.type){
case APPEND:
return { name: state.name +'sb1'};
case REMOVE:
return { name: state.name + 'sb2'};
default:
return state;
}
}
export default personReducer
//reducerNum.js
import {ADD_COUNT,SUB_COUNT} from './constants'
// 1.定义一个状态(数据)
let initialState = {
count: 0
}
// 利用reducer将store和action串联起来
function reducerNum(state = initialState, action){
console.log(state,action)
switch(action.type){
case ADD_COUNT:
return { count: state.count + action.num};
case SUB_COUNT:
return { count: state.count + action.num };
default:
return state;
}
}
export default reducerNum
//reducer.js
import {combineReducers } from 'redux'
import reducerNum from './reducerNum';
import personReducer from './personReducer'
const reducers = combineReducers({
reducerNum,
personReducer
});
export default reducers;
//store.js
import { createStore } from 'redux'
import reducers from './reducer'
// 利用store来保存状态(state)
const store = createStore(reducers);
export default store
//Rudexpage.js 使用redux
import React,{useEffect,useState} from 'react'
import store from '../redux/store'
import {addAction,subAction,append,remove} from '../redux/action'
export default function Rudexpage() {
const [count,setCount] =useState(store.getState().reducerNum.count)
const [name,setName] =useState(store.getState().personReducer.name)
useEffect(()=>{
store.subscribe(()=>{
setCount(store.getState().reducerNum.count)
setName(store.getState().personReducer.name)
})
})
const changeADD=(num)=>{
store.dispatch(addAction(5))
}
const changeremove=(num)=>{
store.dispatch(subAction(-5))
}
const changeAPPEND=()=>{
store.dispatch(append())
}
const changeREMOVE=()=>{
store.dispatch(remove())
}
return (
初始数据:{count}修改后的数据{ store.getState().reducerNum.count}初始数据:{name}
)
}