日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

React?Redux管理庫示例詳解_React

作者:單箭頭→ ? 更新時間: 2023-01-20 編程語言

前言:

什么是redux?redux和vuex一樣,都被統稱為狀態管理庫,是核心數據存貯與分發、監聽數據改變的核心所在。

可以簡單說下redux和vuex的區別:

相同點

  • state 共享數據
  • 流程一致:定義全局state,觸發,修改state
  • 原理相似,通過全局注入store。

不同點

  • vuex定義了state、getter、mutation、action四個對象;redux定義了state、reducer、action。
  • vuex觸發方式有兩種commit同步和dispatch異步;redux同步和異步都使用dispatch
  • vuex中state統一存放,方便理解;reduxstate依賴所有reducer的初始值
  • vuex有getter,目的是快捷得到state;redux沒有這層,react-redux mapStateToProps參數做了這個工作。
  • vuex中mutation只是單純賦值(很淺的一層);redux中reducer只是單純設置新state(很淺的一層)。他倆作用類似,但書寫方式不同
  • vuex中action有較為復雜的異步ajax請求;redux中action中可簡單可復雜,簡單就直接發送數據對象({type:xxx, your-data}),復雜需要調用異步ajax(依賴redux-thunk插件)。
  • Redux 使用的是不可變數據,而Vuex的數據是可變的。Redux每次都是用新的state替換舊的state,而Vuex是直接修改
  • Redux 在檢測數據變化的時候,是通過 diff 的方式比較差異的,而Vuex其實和Vue的原理一樣,是通過 getter/setter來比較的

vuex 數據交互 思維圖:

redux數據交互思維圖:

接下來詳細說說redux:

配置總共分為三部分

一.actions:負責收集并向reduces提交state的變化,自身可分為兩部分actions類型和actions函數創建

(1)actions —type 常量類型,主負責向reduces

(2)actions —fn 函數創建 組件中觸發提交函數

二.reducers 更新state狀態,可根據state數據類型拆分成單個reducer,把reducers細化,后面通過集合構建出最終的大state

三.全局只需要有一個store,不需要像網站中資料介紹的在每一個組件一樣去初始化一個store,一個項目集合在這初始化一次就可以;

store.dispatch() // 提交

store.sbuscribe() // 組件中監聽reducer的變化,即state的變化回調

store.getState() // 獲取state的值,通常和store.sbuscribe() 結合使用

源碼部分:

目錄配置

actions:

index.js

/* actions 類型
* TYPE_GET_LIST 這是一個關于點擊類型獲取列表的定義
*/
import {TYPE_GET_LIST,IS_LOGIN} from "./type"
/* actions 創建函數
*actions 創建函數和actions是兩個概念
*/
export function getType(opt){
  return {type: TYPE_GET_LIST, opt}
}
export function isLogin(flag){
  return {type: IS_LOGIN, flag}
}

type.js

/* actions 類型type */
export const TYPE_GET_LIST = "TYPE_GET_LIST";
export const IS_LOGIN = "IS_LOGIN";
/* 其他常量 */
export const otherType = {
  TO_DO: "TO_DO"
}

reducers

index.js

/**
 * redux 管理入口
 */
import {combineReducers} from "redux"
import userBasketReducer from './userReducer';
import {TYPE_GET_LIST, IS_LOGIN} from "../actions/type"
/* 不同數據結構的單個state */
function typeInfo(state={}, action) {
  console.log(state, action, "這個是tyInfo的信息");
  switch (action.type) {
    case TYPE_GET_LIST: return Object.assign({}, state, {typeInfo: action.opt});
    default: return state;
  }
};
function isLogin(state=false, action) {
  console.log(state, action);
  switch (action.type) {
    case IS_LOGIN: return Object.assign({}, state, {isLogin: action.flag});
    case ....; // 
    default: return state;
  }
};
// 匯總成一個大的state,供全局使用
const reducers = combineReducers({
  userBasket: userBasketReducer,
  typeInfo,
  isLogin
});
export default reducers;

store

import { createStore } from 'redux'
import reducers from '../reducers'
const store = createStore(reducers)
export default store;

至此,一個完整的redux搭建成功,需要拓展什么樣的業務只需要根據自己的業務定義常量函數名和創建函數就可以了,然后通過在組件中dispatch分發的方式提交,就能直接掛載到state對象上供組件間相互使用。

接下來看看如何在組件中使用:

如何提交:

在組件中引入store庫,和函數創建的方法

import {isLogin} from "../../redux/actions"
import store from "../../redux/store";
// 提交
store.dispatch(isLogin({flag: true})) // 登錄成功賦值更新已登錄邏輯

如何動態獲取監聽改變的值監聽,全局監聽state的值

import store from "../../redux/store";
store.subscribe(() => {
			const { selectedFolderId } = store.getState().selectedFolderId;
			this.setState({
				checkFolderId: selectedFolderId
			});
	});

Redux 將組件區分為 容器組件 和 UI 組件

  • 前者會處理邏輯
  • 后者只負責顯示和交互,內部不處理邏輯,狀態完全由外部掌控

Provider

看我上邊那個代碼的頂層組件4個字。對,你沒有猜錯。這個頂級組件就是Provider,一般我們都將頂層組件包裹在Provider組件之中,這樣的話,所有組件就都可以在react-redux的控制之下了,但是store必須作為參數放到Provider組件中去

<Provider store = {store}>
    <App />
<Provider>

這個組件的目的是讓所有組件都能夠訪問到Redux中的數據。

connect 的使用:

connect(mapStateToProps, mapDispatchToProps)(MyComponent)

mapStateToProps 把Redux中的數據映射到React中的props中去。

如:

    const mapStateToProps = (state) => {
      return {
      	// prop : state.xxx  | 意思是將state中的某個數據映射到props中
        foo: state.bar
      }
    }

組件中:

class Foo extends Component {
    constructor(props){
        super(props);
    }
    render(){
        return(
        	// 這樣子渲染的其實就是state.bar的數據了
            <div>this.props.foo</div>
        )
    }
}
Foo = connect()(Foo);
export default Foo;

mapDispatchToProps 把各種dispatch也變成了props讓你可以直接使用

const mapDispatchToProps = (dispatch) => { // 默認傳遞參數就是dispatch
  return {
    onClick: () => {
      dispatch({
        type: 'increatment'
      });
    }
  };
}
class Foo extends Component {
    constructor(props){
        super(props);
    }
    render(){
        return(
        	
             <button onClick = {this.props.onClick}>點擊increase</button>
        )
    }
}
Foo = connect()(Foo);
export default Foo;

可以直接通過this.props.onClick,來調用dispatch,這樣子就不需要在代碼中來進行store.dispatch了

如果哪兒不懂可以留言我會快速回復,拆分的比較細,有些地方可能沒必要拆分,完全是為了自己練習和做個筆記,也方便大家閱讀

原文鏈接:https://blog.csdn.net/weixin_42498482/article/details/128375422

欄目分類
最近更新