1、下载相关依赖
npm i [email protected] [email protected] [email protected] [email protected] [email protected] [email protected] @types/[email protected] @types/[email protected] @types/[email protected]
store - state - reducer - actions
2、configureStore
import { createStore, applyMiddleware } from "redux" import thunkMiddleware from 'redux-thunk' import { createLogger } from 'redux-logger' import reducers from "./reducers" const loggerMiddleware: any = createLogger() let middlewares = [thunkMiddleware] if (process.env.NODE_ENV == 'development') { middlewares.push(loggerMiddleware) } let composeEnhancers = applyMiddleware(...middlewares) export default function configureStore(initialState?: any) { return composeEnhancers(createStore)(reducers, initialState) }
3、reducers
import { combineReducers } from 'redux' import test from "./reducers/test"; const reducers = combineReducers({ test }) export default reducers;
reducers/test.ts
import * as constants from "../actionTypes" import { ITest } from "../states/test"; const initialState: ITest = { count: 0 } interface ITestAction { type: string data: number } export default function addCount( state: ITest = initialState, action: ITestAction ) { switch (action.type) { case constants.ADD_COUNT: return { ...state, count: state.count + 1 } case constants.SUB_COUNT: return { ...state, count: state.count - 1 } case constants.SET_COUNT: return { ...state, count: action.data } default: return state } }
action types
// test action type export const ADD_COUNT = "ADD_COUNT" export const SUB_COUNT = "SUB_COUNT" export const SET_COUNT = "SET_COUNT"
4、页面引入及使用
import * as React from "react"; import { connect } from "react-redux"; import * as dataAPI from '../../api/dataAPI'; import { IRootState } from "../../redux/states"; import * as test from "../../redux/reducers/test" import { ADD_COUNT } from "../../redux/actionTypes"; const Login = ({count, addCount}) => { const testApi = () => { dataAPI.getBlockNumber().then(res => { console.log(res) }) } const add = () => { addCount(1) setTimeout(() => { console.log('>>>',count) }, 3000); } testApi() return ( <div className="signFlowLoginPage"> <div>测试redux数据:{count}</div> <button onClick={add}>+</button> <button>-</button> <button>15</button> </div> ); } export default connect( (state: IRootState) => { console.log(">>>>>", state) return { count: state.test.count } }, dispatch => ({ addCount: (num) => dispatch({type: ADD_COUNT, num} ) }) )(Login);
标签:基本,COUNT,..,记录,redux7,count,state,import,redux From: https://www.cnblogs.com/Nyan-Workflow-FC/p/17059761.html