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目录
- 1、
index.tsx
React-Redux
提供Provider
组件,可以让容器组件拿到state。传送门
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();
- 2、新建
store.ts
文件
createStore
接受3个参数:reducer, preloadedState, enhancer。传送门
reducer
reducer(previousState,action) => newState
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;
- 3、新建
rootReducer.ts
文件
combineReducers
用于 Reducer 的拆分
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;
- 4、新建Home目录,把App组件迁移到此目录,并重命名为Home。增加HomeAction.ts和HomeReducer.ts文件。
- HomeAction.ts
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: ''})}
- HomeReducer.ts
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;
}
}
- Home.tsx
bindActionCreators
用来把{type: 'EXAMPLE', payload: 'tttt'}
转为dispatch({type: 'EXAMPLE', payload: 'tttt'})
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);
- 新建HomeActionCreators.ts,使用bindActionCreators。(此文件与HomeAction.ts二选一)
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的创建函数
-
src
目录下新建Iron
目录,包括IronRedux.ts
、Iron.tsx
,其中IronRedux.ts
可直接输入sr
自动生产模版;
Iron.tsx
文件如下
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);
笔记
- React通过redux-persist持久化数据存储
- TypeSearch
-
react-redux
一般把action和reducer分别建文件;iron-redux
是建一个总的redux文件。 -
redux-saga
是一个用于管理应用程序 Side Effect(副作用,例如异步获取数据,访问浏览器缓存等)的 library,它的目标是让副作用管理更容易,执行更高效,测试更简单,在处理故障时更容易。传送门 - 使用hooks编写redux。传送门