前端學習--React(3)

一、Redux

集中狀態管理工具,不需要react即可使用,每個store的數據都是獨立于組件之外的

vue小鏈接:vuex/pinia

基本使用

Redux將數據修改流程分成三個概念,state、action和reducer

state -?一個對象 存放我們管理的數據狀態

action - 一個對象 描述你如何修改數據

reducer - 一個函數 根據action的描述生成新的state

<button id="decrement">-</button>
<span id="count">0</span>
<button id="increment">+</button><script src="https://unpkg.com/redux@latest/dist/redux.min.js"></script><script>// 1. 定義reducer函數 // 作用: 根據不同的action對象,返回不同的新的state// state: 管理的數據初始狀態// action: 對象 type 標記當前想要做什么樣的修改function reducer (state = { count: 0 }, action) {// 數據不可變:基于原始狀態生成一個新的狀態 所以要返回新對象if (action.type === 'INCREMENT') {return { count: state.count + 1 }}if (action.type === 'DECREMENT') {return { count: state.count - 1 }}return state}// 2. 使用reducer函數生成store實例const store = Redux.createStore(reducer)// 3. 通過store實例的subscribe訂閱數據變化// 回調函數可以在每次state發生變化的時候自動執行store.subscribe(() => {console.log('state變化了', store.getState())document.getElementById('count').innerText = store.getState().count})// 4. 通過store實例的dispatch函數提交action更改狀態 const inBtn = document.getElementById('increment')inBtn.addEventListener('click', () => {// 增store.dispatch({type: 'INCREMENT'})})const dBtn = document.getElementById('decrement')dBtn.addEventListener('click', () => {// 減store.dispatch({type: 'DECREMENT'})})// 5. 通過store實例的getState方法獲取最新狀態更新到視圖中</script>

react中使用redux

相關工具

Redux Toolkit 簡化redux書寫邏輯

react-redux 鏈接Redux和React的中間件

npm i @reduxjs/toolkit react-redux

?安裝成功

目錄創建

創建src/store,modules存放子模塊

counterStore.js

//1 導入并創建store
import {createSlice} from "@reduxjs/toolkit"const counterStore = createSlice({name:'counter',// 初始狀態initialState:{count:0},// 更新狀態的方法reducers:{inscrement(state){state.count++},descrement(state){state.count --}}
})const {inscrement, descrement} = counterStore.actions
const reducer = counterStore.reducerexport{inscrement,descrement
}export default reducer

store/index.js

集成store/modules中所有子模塊

import { configureStore } from "@reduxjs/toolkit";
import counterReducer from "./modules/counterStore"// 將子模塊中的所有store合成一個根store方便訪問
const store = configureStore({reducer:{counter:counterReducer,}
})export default store

src/index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import store from "./store"
import { Provider } from 'react-redux';const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(// 通過react-redux提供的Provider 給組件注入store 使得redux定義的store能夠被react組件使用<Provider store={store}><App /></Provider>
);

App.js

useDispatch() 通過這個來派發reducer修改狀態

import { useSelector, useDispatch } from "react-redux";
import {inscrement, descrement} from "./store/modules/counterStore"
function App() {const { count } = useSelector(state => state.counter)const dispatch = useDispatch()return (<div className="App"><button onClick={() => dispatch(inscrement())}>+</button>{count}<button onClick={() => dispatch(descrement())}>-</button></div>);
}export default App;

然后就完成了:

進階版-提交action時傳參

counterStore.js

增加了一個addToNum函數

//1 導入并創建store
import {createSlice} from "@reduxjs/toolkit"const counterStore = createSlice({name:'counter',// 初始狀態initialState:{count:0},// 更新狀態的方法reducers:{inscrement(state){state.count++},descrement(state){state.count --},addToNum(state, action){// dispatch調用該方法時傳入的參數就存放在action.payloadstate.count += action.payload}}
})const {inscrement, descrement, addToNum} = counterStore.actions
const reducer = counterStore.reducerexport{inscrement,descrement,addToNum
}export default reducer

?App.js

增加了兩個值,傳入不同參數

import { useSelector, useDispatch } from "react-redux";
import {inscrement, descrement, addToNum} from "./store/modules/counterStore"
function App() {const { count } = useSelector(state => state.counter)const dispatch = useDispatch()return (<div className="App"><button onClick={() => dispatch(inscrement())}>+</button>{count}<button onClick={() => dispatch(descrement())}>-</button><button onClick={() => dispatch(addToNum(10))}>+ 10</button><button onClick={() => dispatch(addToNum(-10))}>- 10</button></div>);
}export default App;

再進階版-異步狀態操作

channelStore.js

import {createSlice} from '@reduxjs/toolkit'
import axios from 'axios'const channelStore = createSlice({name:'channel',initialState:{channelList:[]},reducers:{getChannels(state, action){state.channelList = action.payload}}
})const {getChannels} = channelStore.actions//單獨寫一個異步action的函數 異步操作處理完畢后再調用同步action修改狀態
const getChannelList = () => {return async(dispatch) => {const res = await axios.get('http://geek.itheima.net/v1_0/channels')dispatch(getChannels(res.data.data.channels))}
}export {getChannelList}const reducer = channelStore.reducer
export default reducer

?App.js

import { useSelector, useDispatch } from "react-redux";
import {inscrement, descrement, addToNum} from "./store/modules/counterStore"
import {getChannelList} from "./store/modules/channelStore"
import {useEffect} from 'react'
function App() {const { count } = useSelector(state => state.counter)const { channelList } = useSelector(state => state.channel)const dispatch = useDispatch()useEffect(()=> {dispatch(getChannelList())}, [dispatch])return (<div className="App"><button onClick={() => dispatch(inscrement())}>+</button>{count}<button onClick={() => dispatch(descrement())}>-</button><button onClick={() => dispatch(addToNum(10))}>+ 10</button><button onClick={() => dispatch(addToNum(-10))}>- 10</button><ul>{channelList.map(item => <li key={item.id}>{item.name}</li>)}</ul></div>);
}export default App;

調試工具redux devtools

直接在chorme商店里下載

?

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/164145.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/164145.shtml
英文地址,請注明出處:http://en.pswp.cn/news/164145.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

1688API如何獲取商品詳情信息(關鍵詞搜索商品列表),1688API接口開發系列

1688商品詳情接口是指1688平臺提供的API接口&#xff0c;用于獲取商品詳情信息。通過該接口&#xff0c;您可以獲取到商品的詳細信息&#xff0c;包括商品標題、價格、庫存、描述、圖片等。 要使用1688商品詳情接口&#xff0c;您需要先申請1688的API權限&#xff0c;并獲取ac…

UML建模圖文詳解教程01——Enterprise Architect安裝與使用

版權聲明 本文原創作者&#xff1a;谷哥的小弟作者博客地址&#xff1a;http://blog.csdn.net/lfdfhl Enterprise Architect概述 官方網站&#xff1a;https://www.sparxsystems.cn/products/ea/&#xff1b;圖示如下&#xff1a; Enterprise Architect是一個全功能的、基于…

Python入門02 算術運算符及優先級

目錄 1 REPL2 啟動3 算術運算符4 算術運算符的優先級5 清除屏幕總結 上一節我們安裝了Python的開發環境&#xff0c;本節我們介紹一下REPL的概念 1 REPL 首先解釋一下python執行代碼的一個交互環境的定義&#xff1a; Python REPL&#xff08;Read-Eval-Print Loop&#xff0c…

靠這份求職指南找工作,穩了!

大家好&#xff0c;我是魚皮。為了幫助朋友們更好的準備秋招&#xff0c;我們精心匯總整理了 編程導航星球 內魚友反饋的 200 多個高頻求職問題和 150 多篇面經、以及最新秋招企業投遞信息表&#xff0c;解答大家的求職困惑。 一、最新秋招投遞信息表 目前已匯總整理了 600 多家…

C百題--3.求未知數

1.問題描述 一個正整數&#xff0c;它加上100后是一個完全平方數&#xff0c;再加上168又是一個完全平方數&#xff0c;請問該數是多少&#xff1f; 2.解決思路 遍歷這個數&#xff0c;讓其從1開始&#xff0c;到100000結束 3.代碼實現 #include<stdio.h> #include&…

2.C語言--鏈表-頭插、頭刪、尾插、尾刪、查找、插入和刪除

文章目錄 簡介動態順序表結構體1.頭插功能2.頭刪功能3.尾插功能4.尾刪功能5.查找功能6.插入功能6.1 指定位置之&#xff08;前&#xff09;去插入一個節點6.2 指定位置之&#xff08;后&#xff09;去插入一個節點 7.刪除功能7.1 刪除指定位置的數據-時間復雜度O(N)7.2 刪除指定…

配置hikari數據庫連接池時多數據源不生效

1.原始配置&#xff0c;改造前&#xff1a; spring:# 配置數據源信息datasource:dynamic:#設置默認的數據源或者數據源組,默認值即為masterprimary: masterstrict: truedatasource:#這里采用了配置文件取值的方式&#xff0c;可以直接替換為數據庫連接master:url: jdbc:postgr…

【LLS-Player】音視頻幀的回調過程

RtdSinkInterface 實現者用于從SDK獲取音視頻幀 class RtdSinkInterface {public:virtual ~RtdSinkInterface() = default;virtual void OnAudioFrame(const RtdAudioFrame& fra

電子學會C/C++編程等級考試2023年03月(一級)真題解析

C/C++等級考試(1~8級)全部真題?點這里 第1題:字符長方形 給定一個字符,用它構造一個長為4個字符,寬為3個字符的長方形,可以參考樣例輸出。 時間限制:1000 內存限制:65536輸入 輸入只有一行, 包含一個字符。輸出 該字符構成的長方形,長4個字符,寬3個字符。樣例輸入…

如何使用Fiddler進行弱網測試

測試APP、web經常需要用到弱網測試&#xff0c;也就是在信號差、網絡慢的情況下進行測試。我們自己平常在使用手機APP時&#xff0c;在地鐵、電梯、車庫等場景經常會遇到會話中斷、超時等情況&#xff0c;這種就屬于弱網。 普通的弱網測試可以選擇第三方工具對帶寬、丟包、延時…

python數據類型之字典、元組

一、字典 1、定義字典 字典是 有序&#xff08;3.6以前無序&#xff09;、鍵不重復 且 元素只能是鍵值對的可變的 個 容器。鍵不重復&#xff0c;重復則會被覆蓋 如下定義一個字典 # 使用大括號 {} 來創建空字典 test_dic1 {} # 使用內建函數 dict() 創建字典&#xff1a;…

【華為OD題庫-032】數字游戲-java

題目 小明玩一個游戲。系統發1n張牌&#xff0c;每張牌上有一個整數。第一張給小明&#xff0c;后n張按照發牌順序排成連續的一行。需要小明判斷&#xff0c;后n張牌中&#xff0c;是否存在連續的若干張牌&#xff0c;其和可以整除小明手中牌上的數字. 輸入描述: 輸入數據有多組…

嵌入式基礎知識學習:Flash、EEPROM、RAM、ROM

https://blog.csdn.net/y673533511/article/details/87913989 FLASH存儲器又稱閃存&#xff0c;它結合了ROM和RAM的長處&#xff0c;不僅具備電子可擦出可編程(EEPROM) 的性能&#xff0c;還不會斷電丟失數據同時可以快速讀取數據 (NVRAM 的優勢)&#xff0c;U 盤和MP3 里用的…

[論文筆記]MatchPyramid

引言 又一篇文本匹配論文Text Matching as Image Recognition,論文題目是 文本匹配當成圖像識別。 挺有意思的一篇工作,我們來看它是如何實現的。 作者受到卷積神經網絡在圖像識別中成功應用的啟發,其中神經元可以捕獲很多復雜的模式,作者提出將文本匹配看作是圖像識別任…

DDD落地:從網易新聞APP重構,看DDD的巨大價值

尼恩說在前面 在40歲老架構師 尼恩的讀者交流群(50)中&#xff0c;最近有小伙伴拿到了一線互聯網企業如阿里、滴滴、極兔、有贊、希音、百度、網易、美團的面試資格&#xff0c;遇到很多很重要的面試題&#xff1a; 談談你的DDD落地經驗&#xff1f; 談談你對DDD的理解&#x…

GEE:梯度提升樹(Gradient Boosting Tree)分類教程(樣本制作、特征添加、訓練、精度、參數優化、貢獻度、統計面積)

作者:CSDN @ _養樂多_ 本文將介紹在Google Earth Engine (GEE)平臺上進行梯度提升樹(Gradient Boosting Tree)分類的方法和代碼,其中包括制作樣本點教程(本地、在線和本地在線混合制作樣本點,合并樣本點等),加入特征變量(各種指數、紋理特征、時間序列特征、物候特征…

OpenStack云計算平臺-啟動一個實例

目錄 一、創建虛擬網絡 ?二、創建m1.nano規格的主機 三、生成一個鍵值對 四、增加安全組規則 ?五、啟動一個實例 1、確定實例選項 2、創建實例 3、使用虛擬控制臺訪問實例 4、驗證能否遠程訪問實例 一、創建虛擬網絡 下面的說明和框圖使用示例IP 地址范圍。你必須依…

Altium Designer學習筆記12

把幾個層理解下&#xff1a; layer名稱功能說明信息Toplayer信號層銅箔層&#xff0c;電氣連接的層Bottomlayer信號層銅箔層&#xff0c;電氣連接的層Internal Planes內層連接地和電源上&#xff0c;一般情況下不布線&#xff0c;是由整片銅膜組成的Mechanical 1機械層電路板機…

String 、StringBuffer 和 StringBuilder 的區別?

String 使用 String 聲明一個字符串的時候&#xff0c;該字符串會存放在堆中的字符串常量池中。因為在java中所有的String 都是以常量表示&#xff0c;且由 final 修飾&#xff0c;因此在線程池中它的線程是安全的 且 不可變的 。每個 String 在被創建后就不再發生任何變化。 …