react + react-redux + iron-redux

2020-08-10  本文已影响0人  w_tiger

简述

搭建基于redux、react-redux、iron-redux的脚手架,此demo仅做个人练习使用。
Home目录是react-redux;
Iron目录是iron-redux。

一、利用create-react-app创建react的ts项目

yarn create react-app antd-demo-ts --template typescript

二、src目录

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { Switch, Route } from 'react-router';
import { createBrowserHistory, History } from 'history'
import { ConnectedRouter } from 'connected-react-router';
import './index.css';
import Home from './App';
import Iron from './Iron/Iron';
import * as serviceWorker from './serviceWorker';
import useCreateStore from './store';

// Create a history of your choosing (we're using a browser history in this case)
const history: History = createBrowserHistory();
const store = useCreateStore(history);

ReactDOM.render(
  <Provider store={store}>
    <ConnectedRouter history={history}>
      <> { /* your usual react-router v4/v5 routing */ }
        <Switch>
          <Route exact path="/" render={() => (<div>Match</div>)} />
          <Route exact path="/home" render={() => <Home />} />
          <Route exact path="/iron" render={() => <Iron />} />
          <Route render={() => (<div>Miss</div>)} />
        </Switch>
      </>
    </ConnectedRouter>
  </Provider>,
  document.getElementById('root')
);

serviceWorker.unregister();
import { createStore, applyMiddleware, compose } from "redux";
import rootReducer from "./rootReducer";
import thunk from "redux-thunk";
import { History } from 'history';
import { routerMiddleware } from 'connected-react-router';

const initialState = {};

const useCreateStore = (history: History) => {
    const middleWare = [routerMiddleware(history), thunk];
    return (
        process.env.NODE_ENV === 'production' ? (
            createStore(rootReducer(history), initialState, applyMiddleware(...middleWare))
        ) : (
            window.__REDUX_DEVTOOLS_EXTENSION__ ? (
                createStore(rootReducer(history), initialState, compose(applyMiddleware(...middleWare), window.__REDUX_DEVTOOLS_EXTENSION__()))
            ) : (
                createStore(rootReducer(history), initialState, applyMiddleware(...middleWare))
            )
        )
    )
};

export default useCreateStore;
import { combineReducers } from "redux";
import { History } from 'history';
import { connectRouter } from 'connected-react-router';
import { homeReducer } from './Home/HomeReducer';
import { reducer as ironReducer } from './Iron/IronRedux';

const rootReducer = (history: History<any>) =>
  combineReducers({
    router : connectRouter(history),
    home: homeReducer,
    iron: ironReducer
  })

export default rootReducer;
import axios from "axios";

export enum Method {
    Get = 'GET',
    Post = 'POST',
    Put = 'PUT',
    Delete = 'DELETE'
}

/** 创建普通的action */
const createAction = (type: string, payload: any) => () => (dispatch: any) => dispatch({type, payload});
/** 创建接口类的action, 简单示例 */
const createAxiosAction = (type: string, url: string, method = Method.Get ) => () => (dispatch: any) => {
    const promise: any = method === Method.Get ? axios.get(url) : 
                    method === Method.Post ? axios.post(url) : 
                    method === Method.Put ? axios.put(url) : 
                    axios.delete(url);
                    
    promise.then((res: { data: any; }) => dispatch({type, payload: res.data}));
}

export const actions = {
    getHomeData: createAction('EXAMPLE', '_'),
    getApiData: createAxiosAction('GET_API', 'http://apis.juhe.cn/mobile/get')
}

// 抽取创建action的方法为公共方法
// actions = {example: dispatch({type: '', payload: ''})}
const initialState = {
    name: 'L Learn React',
    data: 'WOW'
};

export const homeReducer = (state = initialState, action: any) => {
    switch(action.type) {
        case "EXAMPLE":
            return { ...state, name: action.payload }

        default:
            return state;
    }
}
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import logo from '../logo.svg';
import './Home.css';
import { actions } from './HomeAction';
import * as HomeActionCreators from './HomeActionCreators';

class Home extends Component<any> {
  
  render() {
    console.log('**props:', this.props);
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <p onClick={this.props.getApiData}>
            Edit <code>src/App.tsx</code> and save to reload.
          </p>
          <span className="App-link" onClick={this.props.getHomeData} >
            {this.props.name}
          </span>
        </header>
      </div>
    );
  }
}

// mapStateToProps中的参数state来自全局state
const mapStateToProps = (state: any) => {
  console.log('---state:', state);
  return {
    ...state.home
  }
}
// 以下几种mapDispatchToProps都是可以的
// const mapDispatchToProps = {getHomeData: () => (dispatch: any) => dispatch({type: 'EXAMPLE', payload: 'tttt'})}
// const mapDispatchToProps = { ...actions }
const mapDispatchToProps = (dispatch: any) => bindActionCreators(HomeActionCreators, dispatch);

// export default connect(mapStateToProps, {getHomeData})(Home);
export default connect(mapStateToProps, mapDispatchToProps)(Home);

const createActions = (type: string, payload: any) => () => ({
  type,
  payload
})

const getHomeData = createActions('EXAMPLE', '_');
const getApiData = createActions('GET_API', 'GET_API');

// const getApiData = () => ({
//   type: "GET_API",
//   payload: "GET_API",
// });

export { getHomeData, getApiData };

// 返回action的创建函数
import React from "react";
import { connect } from "react-redux";
import { actions } from "./IronRedux";

class Iron extends React.Component<any> {
  render() {
    return (
      <div>
        <h4 onClick={() => this.props.modifyName('tt')}>iron-redux</h4>
        <div>{this.props.name}</div>
      </div>
    );
  }
}

const mapStateToProps = (state: any) => ({ ...state.iron });
const mapDispatchToProps = { ...actions };

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

笔记

上一篇下一篇

猜你喜欢

热点阅读