安装:
npm install redux react-redux redux-thunk redux-logger
创建文件:
src/store/index.ts:
import { createStore, applyMiddleware } from 'redux' import thunkMiddleware from 'redux-thunk' import { createLogger } from 'redux-logger' import rootReducer from '../reducers' const middlewares = [ thunkMiddleware, createLogger() ] export default function configStore() { const store = createStore(rootReducer, applyMiddleware(...middlewares)); return store; }
src/reducers/index.ts
import { combineReducers } from "redux" import counter from './counter' export default combineReducers({ counter })
src/reducers/counter.ts
import { ADD } from '../constants/counter' const INITIAL_STATE = { num: 0 } export default function counter(state = INITIAL_STATE, action) { switch (action.type) { case ADD: return { ...state, num: state.num + 1 } default: return state } }
src/actions/counter.ts
import { ADD } from '../constants/counter' export const add = () => { return { type: ADD } } export function asyncAdd() { return dispatch => { setTimeout(() => { dispatch(add()) }, 2000) } }
src/constants/counter.ts
export const ADD = 'ADD';
app.tsx
import React, { Component } from 'react' import { Provider } from 'react-redux' import configStore from './store' import './app.scss' const store = configStore(); class App extends Component { render() { // this.props.children 是将要会渲染的页面 return ( <Provider store={store} > {this.props.children} </Provider> ) } } export default App