react+typescript项目中使用redux

  • Post author:
  • Post category:其他




1.项目目录

在这里插入图片描述



2.新建index.ts文件,初始化一个增强store仓库

import { createStore, applyMiddleware, StoreEnhancer, StoreEnhancerStoreCreator, Store } from 'redux';
import thunk from 'redux-thunk';
import reducer from './reducers/index';

// 生成store增强器 
const storeEnhancer: StoreEnhancer = applyMiddleware(thunk);
const storeEnhancerStoreCreator: StoreEnhancerStoreCreator = storeEnhancer(createStore);

const store: Store = storeEnhancerStoreCreator(reducer);

export default store;



3.新建action_types.ts文件

export const ADD = 'ADD';
export const DELETE = 'DELETE';



4.新建addReducer.ts,配置reducer,reducer模块化

import * as types from '../action_types';
import { AnyAction } from 'redux';

// 定义参数接口
export interface AddState {
  number: number
}

// 初始化state
let initialState: AddState = {
  number: 1
};

// 返回一个reducer
export default (state: AddState = initialState, action: AnyAction) => {
  switch (action.type) {
    case types.ADD:
    // payload为传入的参数
      return { number: state.number + action.payload };
    default:
      return state;
  }
};



5.新建index.ts文件,合并reducer

import { combineReducers, ReducersMapObject, AnyAction, Reducer } from 'redux';
import addReducer, { AddState } from './addReducer';
import deleteReducer, { DeleteState } from './deleteReducer';

// 合并reducers,模块化
export interface CombinedState {
  addReducer: AddState,
  ...
  ...
  ...
}
const reducers: ReducersMapObject<CombinedState, AnyAction> = {
  addReducer,
  deleteReducer
};
const reducer: Reducer<CombinedState, AnyAction> = combineReducers(reducers);

export default reducer;



6.挂载到App上

import React, { Component } from 'react';
import Home from './pages/home';
import { Provider } from 'react-redux';
import store from './store';


export default class App extends Component {
  render() {
    return (
      <Provider store={store}>
        <Home />
      </Provider>
    );
  }
}



7.使用

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Dispatch } from 'redux';
import { AddState } from 'src/store/reducers/addReducer';
import { CombinedState } from 'src/store/reducers';
import * as types from 'src/store/action_types';

class Home extends Component<Props> {
  render() {
    const { number, add } = this.props;
    return (
      <div>
        <p>{number}</p>
        <button onClick={() => add(5)}>增加</button>
      </div>
    );
  }
}
// map函数,类似vue的map函数,只不过这里要自己写
const mapStateToProps = (state: CombinedState): AddState => state.addReducer;
const mapDispatchToProps = (dispatch: Dispatch) => {
  return {
    add(num: number = 1) {
      // payload为参数
      dispatch({ type: types.ADD, payload: num });
    }
  };
};

type Props = ReturnType<typeof mapStateToProps> & ReturnType<typeof mapDispatchToProps>

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Home);



版权声明:本文为qq_42760405原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。