最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Redux模塊化拆分reducer函數(shù)流程介紹

 更新時間:2022年09月29日 09:43:38   作者:月光曬了很涼快  
Reducer是個純函數(shù),即只要傳入相同的參數(shù),每次都應返回相同的結果。不要把和處理數(shù)據(jù)無關的代碼放在Reducer里,讓Reducer保持純凈,只是單純地執(zhí)行計算,這篇文章主要介紹了Redux拆分reducer函數(shù)流程

1. 概述

使用 redux 庫中提供的 combineReducers 方法,可以將多個拆分 reducer 函數(shù)合并成統(tǒng)一的 reducer 函數(shù),提供給 createStore 來使用。我們可以將 Redux 進行模塊化拆分,再利用這個函數(shù),將多個拆分 reducer 函數(shù)合并成統(tǒng)一的 reducer 函數(shù),再傳給 createStore 來使用。

2. 方式1-單純文件拆分

redux 入口文件(store/index.js):

// 導入redux中的createStore創(chuàng)建倉庫數(shù)據(jù)的方法
// combineReducers 用來合并多個拆分后的 reducer方式,返回一個新 reducer
// applyMiddleware 擴展redux功能
import { createStore, combineReducers, applyMiddleware } from 'redux'
// 配合瀏覽器安裝的插件來進行redux調試所用  
// 開發(fā)時有用,生產(chǎn)要關閉
import { composeWithDevTools } from '@redux-devtools/extension'
// 導入拆分開的模塊
import count from './reducers/count'
import film from './reducers/film'
// 合并多個模塊中的 reducer 函數(shù),并且返回一個新的 reducer 函數(shù)
const reducer = combineReducers({
  // key:value
  // key:它是在獲取 state 數(shù)據(jù)時的命名空間名稱,redux 中沒有 dispatch 操作的命名空間名稱
  // 如果你進行了 redux 模塊化拆分,則需要注意 type 的類型名稱不能重名,如果重名則都會執(zhí)行
  // type: 以拆分后的文件名稱為前綴:xxx_type 類型名,不會重名
  // value:拆分后的 reducr 純函數(shù)
  count,
  film
})
const store = createStore(
  reducer,
  composeWithDevTools()
)
// 導出
export default store

計數(shù)模塊(count.js):

// 計數(shù)模塊
// 初始state數(shù)據(jù)
const initState = {
  num: 100
}
// 定義一個純函數(shù)reducer,專門用來操作state中的數(shù)據(jù),要返回一個新的state
const reducer = (state = initState, action) => {
  if (action.type === 'count_add_num') return { ...state, num: state.num + action.payload }
  return state;
}
// 導出
export default reducer

電影列表模塊(film.js):

// 電影列表展示模塊
// 初始state數(shù)據(jù)
const initState = {
  nowplayings: []
}
// 定義一個純函數(shù)reducer,專門用來操作state中的數(shù)據(jù),要返回一個新的state
const reducer = (state = initState, action) => {
  if (action.type === 'film_set_nowplayings') return { ...state, nowplayings: action.payload }
  return state;
}
// 導出
export default reducer

計數(shù)器模塊的裝飾器函數(shù)(connect.js):

import { connect } from 'react-redux'
// todo... 一會要配置路徑別名,它引入時就會短一些
// 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

計數(shù)器視圖(index.jsx):

// 計數(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

上面是同步操作的模塊拆分(針對計數(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進行模塊拆分

關于 Redux 的中間件的原理,可以去閱讀下面這篇文章,文章寫得非常精彩!

傳送門

概述:

redux-thunk 它是由 redux 官方開發(fā)出來的 redux 中間件,它的作用:解決 redux 中使用異步處理方案。redux-thunk 中間件可以允許在 connect 參數(shù) 2 中派發(fā)任務時返回的是一個函數(shù),此函數(shù)形參中,redux-thunk 會自動注入一個 dispatch 派發(fā)函數(shù),從而讓你調用 dispath 函數(shù)來派發(fā)任務給 redux,從而實現(xiàn)異步處理。

安裝:

yarn add redux-thunk

使用:

上文提到了對異步操作的處理,在上文基礎上,我們修改成使用中間件進行處理的寫法。

index.js:

// 導入redux中的createStore創(chuàng)建倉庫數(shù)據(jù)的方法
// combineReducers 用來合并多個拆分后的 reducer方式,返回一個新 reducer
// applyMiddleware 擴展redux功能
import { createStore, combineReducers, applyMiddleware } from 'redux'
// 配合瀏覽器安裝的插件來進行redux調試所用  
// 開發(fā)時有用,生產(chǎn)要關閉
import { composeWithDevTools } from '@redux-devtools/extension'
// 導入拆分開的模塊
import count from './reducers/count'
import film from './reducers/film'
import thunk from 'redux-thunk'
// 合并多個模塊中的 reducer 函數(shù),并且返回一個新的 reducer 函數(shù)
const reducer = combineReducers({
  count,
  film
})
const store = createStore(
  reducer,
  composeWithDevTools(applyMiddleware(thunk))
)
// 導出
export default store

connect.js:

import { connect } from 'react-redux'
// actions 這是一個對象 {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))
}

到此這篇關于Redux模塊化拆分reducer函數(shù)流程介紹的文章就介紹到這了,更多相關Redux模塊化拆分內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • useEffect中不能使用async原理詳解

    useEffect中不能使用async原理詳解

    這篇文章主要為大家介紹了useEffect中為什么不能使用async的原理詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-07-07
  • React避免子組件無效刷新的三種解決方案

    React避免子組件無效刷新的三種解決方案

    這篇文章主要給大家介紹了React三種避免子組件無效刷新的解決方案,使用React.memo,使用React.useMemo或React.useCallback,將子組件作為children來傳遞這三種方案,文章通過代碼介紹的非常詳細,需要的朋友可以參考下
    2023-08-08
  • 在React中與后端API進行交互的操作步驟

    在React中與后端API進行交互的操作步驟

    在現(xiàn)代Web開發(fā)中,前后端分離的架構已經(jīng)成為一種趨勢,React,作為一種流行的前端庫,常常與后端API進行交互,以實現(xiàn)動態(tài)數(shù)據(jù)更新和用戶體驗優(yōu)化,本文將深入探討如何在React應用中與后端API進行交互,需要的朋友可以參考下
    2025-02-02
  • React中的Hooks路由跳轉問題

    React中的Hooks路由跳轉問題

    這篇文章主要介紹了React中的Hooks路由跳轉問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-12-12
  • 基于React實現(xiàn)無限滾動表格

    基于React實現(xiàn)無限滾動表格

    以文本為例,為了實現(xiàn)無限循環(huán)的視覺效果,我們需要準備兩段相同的文本,并讓第二段文本的頭部銜接在第一段文本的尾部,同時,為兩段文本設置相同的滾動動畫,本文給大家介紹了基于React實現(xiàn)無限滾動表格,需要的朋友可以參考下
    2023-11-11
  • react-router4按需加載(踩坑填坑)

    react-router4按需加載(踩坑填坑)

    這篇文章主要介紹了react-router4按需加載(踩坑填坑),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2019-01-01
  • 比ant更豐富Modal組件功能實現(xiàn)示例詳解

    比ant更豐富Modal組件功能實現(xiàn)示例詳解

    這篇文章主要為大家介紹了比ant更豐富Modal組件功能實現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-11-11
  • React中的Props類型校驗和默認值詳解

    React中的Props類型校驗和默認值詳解

    這篇文章主要為大家詳細介紹了React中的Props類型校驗和默認值,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
    2022-03-03
  • React使用公共文件夾public問題

    React使用公共文件夾public問題

    這篇文章主要介紹了React使用公共文件夾public問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-12-12
  • React State與生命周期詳細介紹

    React State與生命周期詳細介紹

    React將組件(component)看成一個狀態(tài)機(State Machines),通過其內(nèi)部自定義的狀態(tài)(State)和生命周期(Lifecycle)實現(xiàn)并與用戶交互,維持組件的不同狀態(tài)
    2022-08-08

最新評論

饶平县| 石门县| 木里| 白山市| 镇巴县| 南阳市| 沙雅县| 禹州市| 定结县| 通州市| 东港市| 永新县| 柳林县| 仁化县| 五指山市| 遂宁市| 鄂托克旗| 定陶县| 栾城县| 武汉市| 裕民县| 仙居县| 甘孜| 平顺县| 东乡| 错那县| 哈密市| 民丰县| 德令哈市| 木兰县| 丽水市| 乐东| 宁津县| 元谋县| 炉霍县| 深圳市| 宝山区| 平安县| 清水河县| 丹寨县| 德化县|