網(wǎng)站首頁 編程語言 正文
1. 概述
使用 redux 庫中提供的 combineReducers 方法,可以將多個(gè)拆分 reducer 函數(shù)合并成統(tǒng)一的 reducer 函數(shù),提供給 createStore 來使用。我們可以將 Redux 進(jìn)行模塊化拆分,再利用這個(gè)函數(shù),將多個(gè)拆分 reducer 函數(shù)合并成統(tǒng)一的 reducer 函數(shù),再傳給 createStore 來使用。
2. 方式1-單純文件拆分
redux 入口文件(store/index.js):
// 導(dǎo)入redux中的createStore創(chuàng)建倉庫數(shù)據(jù)的方法
// combineReducers 用來合并多個(gè)拆分后的 reducer方式,返回一個(gè)新 reducer
// applyMiddleware 擴(kuò)展redux功能
import { createStore, combineReducers, applyMiddleware } from 'redux'
// 配合瀏覽器安裝的插件來進(jìn)行redux調(diào)試所用
// 開發(fā)時(shí)有用,生產(chǎn)要關(guān)閉
import { composeWithDevTools } from '@redux-devtools/extension'
// 導(dǎo)入拆分開的模塊
import count from './reducers/count'
import film from './reducers/film'
// 合并多個(gè)模塊中的 reducer 函數(shù),并且返回一個(gè)新的 reducer 函數(shù)
const reducer = combineReducers({
// key:value
// key:它是在獲取 state 數(shù)據(jù)時(shí)的命名空間名稱,redux 中沒有 dispatch 操作的命名空間名稱
// 如果你進(jìn)行了 redux 模塊化拆分,則需要注意 type 的類型名稱不能重名,如果重名則都會執(zhí)行
// type: 以拆分后的文件名稱為前綴:xxx_type 類型名,不會重名
// value:拆分后的 reducr 純函數(shù)
count,
film
})
const store = createStore(
reducer,
composeWithDevTools()
)
// 導(dǎo)出
export default store
計(jì)數(shù)模塊(count.js):
// 計(jì)數(shù)模塊
// 初始state數(shù)據(jù)
const initState = {
num: 100
}
// 定義一個(gè)純函數(shù)reducer,專門用來操作state中的數(shù)據(jù),要返回一個(gè)新的state
const reducer = (state = initState, action) => {
if (action.type === 'count_add_num') return { ...state, num: state.num + action.payload }
return state;
}
// 導(dǎo)出
export default reducer
電影列表模塊(film.js):
// 電影列表展示模塊
// 初始state數(shù)據(jù)
const initState = {
nowplayings: []
}
// 定義一個(gè)純函數(shù)reducer,專門用來操作state中的數(shù)據(jù),要返回一個(gè)新的state
const reducer = (state = initState, action) => {
if (action.type === 'film_set_nowplayings') return { ...state, nowplayings: action.payload }
return state;
}
// 導(dǎo)出
export default reducer
計(jì)數(shù)器模塊的裝飾器函數(shù)(connect.js):
import { connect } from 'react-redux'
// todo... 一會要配置路徑別名,它引入時(shí)就會短一些
// import countAction from '../../store/actionCreators/countAction'
import countAction from '@/store/actionCreators/countAction'
const mapDispatchToProps = dispatch => ({
...countAction(dispatch)
})
export default connect(state => state.count, mapDispatchToProps)
countAction.js:
export default dispatch => ({
add(n = 1) {
dispatch({ type: 'count_add_num', payload: n })
}
})
App.jsx:
import React, { Component } from 'react'
import { Switch, Route, Link } from 'react-router-dom'
import Count from './views/Count'
import Nowplaying from './views/Nowplaying'
class App extends Component {
render() {
return (
<div>
<div>
<Link to='/nowplaying'>nowplaying</Link> --
<Link to='/count'>count</Link>
</div>
<hr />
{/* 定義路由規(guī)則 */}
<Switch>
<Route path="/nowplaying" component={Nowplaying} />
<Route path="/count" component={Count} />
</Switch>
</div>
)
}
}
export default App
計(jì)數(shù)器視圖(index.jsx):
// 計(jì)數(shù)組件
import React, { Component } from 'react'
import connect from './connect'
@connect
class Count extends Component {
render() {
return (
<div>
<h3>{this.props.num}</h3>
<button onClick={() => this.props.add()}>累加NUM</button>
</div>
)
}
}
export default Count
上面是同步操作的模塊拆分(針對計(jì)數(shù)器模塊做的演示),下面是異步操作的模塊化拆分,以電影播放列表為例。
電影模塊的裝飾器函數(shù)(connect.js):
import { connect } from 'react-redux'
import filmAction from '@/store/actionCreators/filmAction'
export default connect(state => state.film, dispatch => filmAction(dispatch))
filmAction.js:
import { getNowPlayingFilmListApi } from '@/api/filmApi'
export default dispatch => ({
add(page = 1) {
getNowPlayingFilmListApi(page).then(ret => {
dispatch({ type: 'film_set_nowplayings', payload: ret.data.films })
})
}
})
// async 和 await 寫法
// export default dispatch => ({
// async add(page = 1) {
// let ret = await getNowPlayingFilmListApi(page)
// dispatch({ type: 'film_set_nowplayings', payload: ret.data.films })
// }
// })
filmApi.js:
import { get } from '@/utils/http'
export const getNowPlayingFilmListApi = (page = 1) => {
return get(`/api/v1/getNowPlayingFilmList?cityId=110100&pageNum=${page}&pageSize=10`)
}
電影模塊視圖(index.jsx):
// 電影展示列表組件
import React, { Component } from 'react'
import connect from './connect'
@connect
class Nowplaying extends Component {
componentDidMount() {
this.props.add()
}
render() {
return (
<div>
{this.props.nowplayings.length === 0 ? (
<div>加載中...</div>
) : (
this.props.nowplayings.map(item => <div key={item.filmId}>{item.name}</div>)
)}
</div>
)
}
}
export default Nowplaying
3. 方式2-使用中間件redux-thunk進(jìn)行模塊拆分
關(guān)于 Redux 的中間件的原理,可以去閱讀下面這篇文章,文章寫得非常精彩!
傳送門
概述:
redux-thunk 它是由 redux 官方開發(fā)出來的 redux 中間件,它的作用:解決 redux 中使用異步處理方案。redux-thunk 中間件可以允許在 connect 參數(shù) 2 中派發(fā)任務(wù)時(shí)返回的是一個(gè)函數(shù),此函數(shù)形參中,redux-thunk 會自動注入一個(gè) dispatch 派發(fā)函數(shù),從而讓你調(diào)用 dispath 函數(shù)來派發(fā)任務(wù)給 redux,從而實(shí)現(xiàn)異步處理。
安裝:
yarn add redux-thunk
使用:
上文提到了對異步操作的處理,在上文基礎(chǔ)上,我們修改成使用中間件進(jìn)行處理的寫法。
index.js:
// 導(dǎo)入redux中的createStore創(chuàng)建倉庫數(shù)據(jù)的方法
// combineReducers 用來合并多個(gè)拆分后的 reducer方式,返回一個(gè)新 reducer
// applyMiddleware 擴(kuò)展redux功能
import { createStore, combineReducers, applyMiddleware } from 'redux'
// 配合瀏覽器安裝的插件來進(jìn)行redux調(diào)試所用
// 開發(fā)時(shí)有用,生產(chǎn)要關(guān)閉
import { composeWithDevTools } from '@redux-devtools/extension'
// 導(dǎo)入拆分開的模塊
import count from './reducers/count'
import film from './reducers/film'
import thunk from 'redux-thunk'
// 合并多個(gè)模塊中的 reducer 函數(shù),并且返回一個(gè)新的 reducer 函數(shù)
const reducer = combineReducers({
count,
film
})
const store = createStore(
reducer,
composeWithDevTools(applyMiddleware(thunk))
)
// 導(dǎo)出
export default store
connect.js:
import { connect } from 'react-redux'
// actions 這是一個(gè)對象 {a:funtion(){}}
import * as actions from '@/store/actionCreators/filmAction'
export default connect(state => state.film, actions)
filmAction.js:
import { getNowPlayingFilmListApi } from '@/api/filmApi'
const addActionCreator = data => ({ type: 'film_set_nowplayings', payload: data })
// 異步
export const add = (page = 1) => async dispatch => {
let ret = await getNowPlayingFilmListApi(page)
dispatch(addActionCreator(ret.data.films))
}
原文鏈接:https://blog.csdn.net/weixin_45605541/article/details/127078701
相關(guān)推薦
- 2023-10-09 Cookie和localStorage存儲的區(qū)別
- 2022-04-20 C++的多態(tài)和虛函數(shù)你真的了解嗎_C 語言
- 2023-03-29 C語言交換奇偶位與offsetof宏的實(shí)現(xiàn)方法_C 語言
- 2022-08-03 Android開發(fā)手冊Chip監(jiān)聽及ChipGroup監(jiān)聽_Android
- 2022-06-12 C#集合之可觀察集合的用法_C#教程
- 2022-10-03 Go?Excelize?API源碼閱讀Close及NewSheet方法示例解析_Golang
- 2022-11-06 修改Nginx配置返回指定content-type的方法_nginx
- 2023-01-01 利用Python腳本實(shí)現(xiàn)傳遞參數(shù)的三種方式分享_python
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支