项目环境搭建
使用create-react-app
CSS使用styled-components
yarn add styled-components
引入reset.css样式
import { createGlobalStyle } from 'styled-components'
import { createStore, applyMiddleware, compose } from 'redux'; + const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; + const store = createStore(reducer, /* preloadedState, */ composeEnhancers( - const store = createStore(reducer, /* preloadedState, */ compose( applyMiddleware(...middleware) ));
使用combineReducer对reducer拆分
修改store下的reducer.js代码
import { combineReducers } from 'redux' import { reducer as headerReducer} from '../components/header/store' export default combineReducers({ header: headerReducer })
使用actionCreators.js和actionTypes.js对store代码优化
使用immutable.js和redux-immutable
yarn add redux-immutable
生成的immutable对象,改对象不可改变
yarn add immutable
如何使用
import {fromJS} from 'immutable' const defaultState = fromJS({ focused: false })
const mapStateToProps = state => { return { focused:state.header.get('focused') } }
export default (state = defaultState, action) => { if (action.type === actionTypes.SEARCH_BLUR) { return state.set('focused', false) } if (action.type === actionTypes.SEARCH_FOCUS) { return state.set('focused', true) } return state }
使用redux-thunk
异步操作不在componentDidMount中操作
放到action
yarn add redux-thunk
后端使用koa koa-router koa-cors mock
模拟后端服务器
前端使用axios
跨域配置 "proxy": "http://localhost:8080"
安装react-router-dom
<BrowserRouter>
<div>
<Header/>
<Route path="/" exact component={Home}/>
<Route path="/detail/:id" exact component={Detail}/>
</div>
</BrowserRouter>
获得pathname
const {pathname} = this.props.location
页面跳转
this.props.history.push('/')
页面重定向
<Redirect from='/...' to='/...' />