redux
基本使用
首先,安装redux
yarn add redux react-redux redux-thunk
在store文件夹下创建index.js
文件,用于创建store对象
// store/index.js
import { createStore } from 'redux'
const store = createStore()
createStore()
有2个参数,第一个参数是reducer,在实际项目中,大量的数据必然不可能只有一个reducer,我们需要将多个reducer进行合并,同时为了结构更清晰,不要在index.js
中进行reducer的合并,而是在store文件夹下再创建一个reducer.js
文件
// store/reducer.js
import { combineReducers } from 'redux'
const cReducer = combineReducers({
...合并操作
})
export default cReducer
然后将reducer.js中合并后的reducer导入,在index.js
中导入
// store/index.js
import { createStore } from 'redux'
import reducer from './reducer'
const store = createStore(reducer, )
现在createStore()
的第一个参数已经完成,然后第二个参数是用于对reducer进行加强的,比如中间件,因此,从redux中导入applyMiddleware
用于合并中间件,同时,为了让redux的调试工具生效,进行如下操作,最后,store也已经完成,将store导出:
// store/index.js
import { createStore, applyMiddleware, compose } from 'redux'
import reducer from './reducer'
import thunk from 'redux-thunk'
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; // 用于redux的调试工具
const store = createStore(
reducer,
composeEnhancers(applyMiddleware(thunk))
)
export default store
现在我们已经有了store,我们需要将store进行共享,才能让别人使用store中的内容,因此,我们来到App.js
,导入store,再从react-redux中导入Provider
,用于将store进行共享
// App.js
import React, { memo } from 'react'
import routes from './router'
import { HashRouter } from 'react-router-dom'
import { renderRoutes } from 'react-router-config'
import AppHeader from 'components/app-header'
import AppFooter from 'components/app-footer'
// ...其他导入
import store from './store'
import { Provider } from 'react-redux'
export default memo(function App() {
return (
<Provider store={store}>
<HashRouter>
<AppHeader />
{renderRoutes(routes)}
<AppFooter />
</HashRouter>
</Provider>
)
})
现在,我们已经完成了redux的最顶层的配置,接下来,需要将具体的reducer放到store/reducer.js
中进行合并,对于具体的组件的reducer的位置,每个人的做法都不同,这里我就将其在具体的组件下再创建一个store文件夹,用于管理该组件具体的redux,并分别创建actionCreators.js
、constants.js
、index.js
、reducer.js
,现在的目录结构就变为:
src
├─ pages
│ ├─ recommend(具体的组件或子组件)
│ ... ├─ store
│ index.js ├─ actionCreators.js
│ ├─ constants.js
│ ├─ index.js
│ └─ reducer.js
├─ store
│ ├─ index.js
│ └─ reducer.js
...
然后在reducer.js
中创建默认的状态defaultState
,用于存放数据;再创建一个reducer函数,第一个参数是state,可以将其默认值设为创建的defaultState
,第二个参数是action,用于根据传入的不同的action来进行不同的操作更新state
// recommend/store/reducer.js
const defaultState = {
topBanners: []
}
function reducer(state = defaultState, action) {
switch(action.type) {
case :
return
}
}
为了区分传入的action,每一个action都有标识的actionType,并且一般设为常量,因此,在store/constants.js
中设置常量,常量的具体命名规则看自己的喜好:
// recommend/store/constants.js
export const CHANGE_TOP_BANNERS = "recommend/CHANGE_TOP_BANNERS"
然后再将常量在store/reducer.js
中导入,并根据不同的action进行不同的操作,最后将reducer导出:
// recommend/store/reducer.js
import * as actionTypes from './constants'
const defaultState = {
topBanners: []
}
function reducer(state = defaultState, action) {
switch(action.type) {
case actionTypes.CHANGE_TOP_BANNERS:
return {...state, topBanners: []}
// return {...state, topBanners: action.topBanners} // 保存传入的数据的操作
default:
return state
}
}
export default reducer
来到store/index.js
,将reducer导入,并再将reducer统一导出
// recommend/store/index.js
import reducer from './reducer'
export {
reducer
}
现在,我们有了具体的reducer了,因此,来到src/store/reducer.js
,将导入的reducer进行合并:
// src/store/reducer.js
import { combineReducers } from 'redux'
import { reducer as recommendReducer } from '../pages/discover/c-pages/recommend/store'
const cReducer = combineReducers({
recommend: recommendReducer,
})
export default cReducer
现在,就能在redux调试工具中看到数据了:
网络请求
现在,我们使用中间件(这里以thunk为例)在redux中发送网络请求,而不是在组件中发送网络请求
来到recommend/store/actionCreators.js
,进行发送网络请求:
// recommend/store/actionCretor.js
import * as actionTypes from './constants'
import { getTopBanners } from 'services/recommend' // 导入发送网络请求的函数
// 当派发这个函数时,就可以来到reducer.js中的reducer函数,根据type进行相应的操作
const changeTopBannerActon = res => ({
type: actionTypes.CHANGE_TOP_BANNERS,
topBanners: res.banners
})
export const getTopBannerAction = () => {
return dispatch => {
getTopBanners().then(res => { // 发送网络请求
dispatch(changeTopBannerActon(res)) // 将数据保存到reducer.js中的state中
})
}
}
注意:这里为什么要使用getTopBannerAction
进行包裹并return一个函数?
// 因为有时候需要传递一些参数来进行操作
export const getTopBannerAction = (参数1, 参数2, ...) => {
return dispatch => {
...发送网络请求并保存数据
}
}
现在,这个网络请求函数我们已经封装好了,然后我们就需要在组件中进行调用,将组件和redux进行关联
// recommend/index.js
import React, { memo } from 'react'
import { connect } from 'react-rudex'
import { getTopBannerAction } from './store/actionCreators' // 导入封装的网络请求函数
function Recommend(props) {
const { getBanners, topBanners } = props;
useEffect(() => {
getBanners();
}, [getBanners])
return (
<div>
<h2>HYRecommend: {topBanners.length}</h2>
</div>
)
}
const mapStateToProps = state => ({ // 这里是state是src/store/index.js中的state
topBanners: state.recommend.topBanners
});
const mapDispatchToProps = dispatch => ({
getBanners: () => {
dispatch(getTopBannerAction())
}
})
export default connect(mapStateToProps, mapDispatchToProps)(memo(Recommend));
注意:在recommend/store/reducer.js
中
// 将
return {...state, topBanners: []}
// 换为
return {...state, topBanners: action.topBanners} // 保存传入的数据的操作
现在,就能在redux调试工具中看到数据了:
使用 redux hook
可以发现,每当一个组件需要和redux进行关联的时候,我们就需要在组件中写上一坨代码:
const mapStateToProps = state => ({ // 这里是state是src/store/index.js中的state
topBanners: state.recommend.topBanners
});
const mapDispatchToProps = dispatch => ({
getBanners: () => {
dispatch(getTopBannerAction())
}
})
export default connect(mapStateToProps, mapDispatchToProps)(memo(Recommend));
这非常的不好,因此,我们使用redux的hook进行简化、重构,重构后的代码如下:
// recommend/index.js
import React, { memo, useEffect } from 'react'
import { useDispatch, useSelector, shallowEqual } from 'react-redux'
import { getTopBannerAction } from './store/actionCreators' // 导入封装的网络请求函数
function Recommend(props) {
// 组件和redux关联,进行操作和获取数据
const dispatch = useDispatch()
const { topBanners } = useSelector(state => ({
topBanners: state.recommend.topBanners
}), shallowEqual)
/* 关于 shallowEqual
connect内部有进行性能优化,对数据进行浅层比较,如果页面所依赖的数据没有发生变化 或 发生变化的数据没有进行依赖,则页面不会重新渲染。
但是 useSelector 并没有进行浅层比较,而是默认使用 === 进行比较,但是函数每次执行时会重新创建字面量,开辟新的地址,因此两次函数的 === 比较结果必然是不同的,因此页面必定会重新渲染。
为了解决这个问题,需要用到另一个 hook :shallowEqual ,使其进行浅层比较。
因此,理论上,只要用到 redux hook,都默认使用上 shallowEqual ,除非是特殊情况,希望只要数据发生改变,页面全部重新渲染。
*/
// 发送网络请求
useEffect(() => {
dispatch(getTopBannerAction)
}, [dispatch])
return (
<div>
<h2>HYRecommend: {topBanners.length}</h2>
</div>
)
}
export default memo(Recommend);