一个 react-router + redux + react-redux 的例子与分析
index.js
import React from 'react' import ReactDom from 'react-dom' import App from './App' ReactDom.render( <App/>, document.getElementById('root') )
没什么好说的
App.js :
import React from 'react' import { createStore, applyMiddleware } from 'redux' import { Provider } from 'react-redux' import thunk from 'redux-thunk' import reducers from './reducers' import RouterMap from './router' let store = createStore(reducers, applyMiddleware(thunk)) const App = () => { return ( <Provider store={ store }> <RouterMap/> </Provider> ) } export default App
代码分析:
- reducers: redux 中的 reducers
- thunk: 异步action 的插件
- applyMiddleware: react 的中间件,用于添加插件
- RouterMap: 路由配置
- Provider:让所有容器组件都可以访问 store
- createStore: redux 生成 store 的方法
例子中的:RouterMap
import React from 'react' // react-router 相关 import { Router, Route, Switch } from 'react-router-dom' // 浏览器的History模式 import createHistory from 'history/createBrowserHistory' // 生成一个redux容器的方法 import { connect } from 'react-redux' // 一个action import { initCity } from '../actions/userinfo' // 组件 import Home from '../containers/Home' import City from '../containers/City' // 创建 history const history = createHistory() class App extends React.Component { render() { return ( <Router history={ history }> <Switch> <Route exact path="/" component={ Home }></Route> <Route path="/city" component={ City }></Route> </Switch> </Router> ) } componentDidMount() { this.props.initCity(cityName) } } function mapStateToProps(state) { return { userInfo: state.userInfo } } function mapDispatchToProps(dispatch, ownprops) { return { initCity: (cityName) => { } } } export default connect( mapStateToProps, mapDispatchToProps )(App)
代码分析:
- connect:
- 该方法接受2个参数,返回一个函数,返回的函数的参数通常 是react 组件,例子是App
- 参数1是函数,函数接收 store 中的 state 作为参数,通常 返回 state 中的数据,例子中的App组件可以通过 this.props.userInfo 获取数据
- 参数2是函数,函数接收 store 中的 dispatch作为第一个参数,通常返回提交action的一些方法,例子中的App组件可以通过 this.props.initCity(cityName) 提交action
- <Router history={ history }> : 传递history 给所有组件,组件就可以通过 this.props.history.push('路由')跳转页面, this.props.history.goBack() 方法返回
- <Route path="/city" component={ City }></Route> : 路由配置
例子中的:reducers
import { combineReducers } from 'redux' export function detailInfo(state = {}, action) { switch (action.type) { case 'GET_DETAIL_INFO': return { ...state, info: action.payload.info } case 'GET_COMMENT_LIST': return { ...state, comments: action.payload.comments } default: return state } } const initialState = {page: 0, likeList: [] } export function userInfo(state = initialState, action) { switch (action.type) { case 'USER_CURRENTCITY': return { ...state, cityName: action.payload.cityName, userName: '小名' } case 'SAVE_HOMEAD': return { ...state, homeAd: action.payload.homeAd } case 'SAVE_LIKELIST': return { ...state, page: state.page + 1, likeList: state.likeList.concat(action.payload.likeList) } case 'SET_ISLOADINGLIKELIST_FLAG': return { ...state, isLoading: action.payload.isLoading } default: return state } } export default combineReducers({ userInfo, detailInfo })
代码分析:combineReducers: 接收一个拆分后 reducer 函数组成的对象,返回一个新的 Reducer 函数
代码中的:所有action ,案例只列举:initCity
import axois from 'axios' export function getDetailInfo(shopId) { return dispatch => axois.get(`/api/detail/info/${shopId}`).then((res) => { dispatch(saveDetailInfo(res.data)) }).catch((error) => { console.log(error) }) } export function saveDetailInfo(res) { return { type: 'GET_DETAIL_INFO', payload: { info: res } } } export function getComments(shopId) { return axois.get(`/api/detail/comment/${shopId}`).then((res) => { dispatch(saveComments(res.data)) }).catch((error) => { console.log(error) }) } export function saveComments(res) { return { type: 'GET_COMMENT_LIST', payload: { comments: res } } }
- axois: ajax请求的插件
- getDetailInfo:
- 该action 返回了一个发送ajax异步请求的函数
- 异步请求成功后 触发一个action : dispatch(saveDetailInfo(res.data))
- 普通的action 通常返回一个对象,它之所以能够返回函数,是由于利用了插件“thunk'”,这个是异步action 的写法
City
import React from 'react' import { connect } from 'react-redux' import { updateCity } from '../../actions/userinfo' import Header from '../../components/Header' import CityList from '../../components/CityList' import CurrentCity from './subpages/CurrentCity' class City extends React.Component { render() { return ( <div> <Header title="选择城市" goBack={ this.goBack.bind(this) }></Header> <CurrentCity currentCityName={ this.props.userInfo.cityName }></CurrentCity> <CityList chooseCity= { this.chooseCity.bind(this) }></CityList> </div> ) } goBack() { this.props.history.goBack() } chooseCity(cityName) { localStore.setItem('USER_CURRENT_CITY', cityName) this.props.initCity(cityName) this.props.history.goBack() } } function mapStateToProps(state) { return { userInfo: state.userInfo } } function mapDispatchToProps(dispatch, ownProps) { return { initCity: (cityName) => { dispatch(updateCity(cityName)) } } } export default connect( mapStateToProps, mapDispatchToProps )(City)
goBack={ this.goBack.bind(this) } : 将组件本身的goBack方法,传递给 Header 组件 , bind的作用是:在Header组件调用该方法时,上下文为City组件的 this
Header
import React from 'react' class Header extends React.Component { render() { return ( <div id="common-header"> <span className="back-icon" onClick={ this.clickHandle.bind(this) }> <i className="icon-chevron-left"></i> </span> <h1>{ this.props.title }</h1> </div> ) } clickHandle() { window.history.back() } } export default Header
Header组件并没有用connect包装,因为它是纯显示的组件,只有跟业务相关的组件,才会用connect容器包装