網站首頁 編程語言 正文
多個組件數據共享
我們之前講解的一直都是只有一個組件需要向redux讀取狀態,也就是Count這個求和組件。那么我們在實際使用redux的場景中,當然是有很多組件一起共享數據才需要使用到redux進行狀態管理啦,現在我們就來看看多個組件通過redux實現數據共享的場景吧~
現在我們創建一個Person組件,同樣的,Person組件的數據也交給redux管理。此時,Count組件也可以從redux中讀取到Person組件的數據,Person組件也可以從redux中讀取到Count組件之前存放在redux中的數據。是不是很方便呢?這就是redux集中式的狀態管理中的多個組件的數據共享。
項目結構:
src ├─App.jsx ├─index.js ├─redux | ├─constant.js | ├─store.js | ├─reducers | | ├─count.js | | └person.js | ├─actions | | ├─count.js | | └person.js ├─containers | ├─Person | | └index.jsx | ├─Count | | └index.jsx
項目展示:
??注意:Count組件部分內容已在前幾篇文章中,在本文中注重的是新增的Person組件與之前的Count組件共享狀態。
閱讀順序:
【Redux工作流程】
【異步action】
【react-redux基本使用與優化】
1.首先在constant.js
中添加我們在Person組件中需要使用的類型:
export const INCREMENT = 'increment' export const DECREMENT = 'decrement' + export const ADD_PERSON = 'add_person'
該模塊是用于定義action對象中type類型的常量模塊,便于管理的同時避免程序員單詞拼寫出錯。
2.編寫Person組件的action文件,用于創建action動作對象以供Person組件使用:
/src/redux/actions/person.js
/* 該文件專門為Person組件生成action動作對象 */ import { ADD_PERSON } from "../constant"; // 創建增加一個person的action動作對象 export const createAddPersonAction = personObj => ({ type: ADD_PERSON, data: personObj })
3.編寫Person組件的reducer文件,用于創建一個為Person組件服務的reducer函數
/src/redux/reducers/person.js
/* 1.該文件用于創建一個為Person組件服務的reducer函數 2.reducer函數會接收到兩個參數,分別為之前的狀態(prevState)和動作對象(action) */ import { ADD_PERSON } from "../constant"; const initState = [{ id: 001, name: 'tom', age: 18 }] export default function personReducer(prevState = initState, action) { const { type, data } = action switch (type) { case ADD_PERSON: return [data, ...prevState] default: return prevState } }
4.redux若只為一個組件服務,store內部存儲的數據不需要任何的標識。但是store中若存放了多個組件的狀態,那么就需要用一個對象將所有的狀態囊括起來,每個狀態都是一組key:value值。
比如,Count組件存儲的狀態為:count:0
。Person組件存儲的狀態為:persons:[]
。
/src/redux/store.js
- import { legacy_createStore as createStore, applyMiddleware } from 'redux'; // 引入combineReducers,用于合并reducer + import { legacy_createStore as createStore, applyMiddleware, combineReducers } from 'redux'; import countReducer from './reducers/count' // 引入為Person組件服務的reducer + import personReducer from './reducers/person'; import thunk from 'redux-thunk' + // 合并reducer + const allReducer = combineReducers({ + count: countReducer, + persons: personReducer + }) // 暴露store - export default createStore(countReducer, applyMiddleware(thunk)) + export default createStore(allReducer, applyMiddleware(thunk))
在原先的store中只存放了一個Count組件的狀態數據,現在新增了Person組件需要使用redux,那么就應該對store.js進行一些修改。
在store.js文件中,從redux中新引入combineReducers函數用于合并reducer;
引入為Person組件服務的reducer;
將原先的countReducer與新引入的personReducer合并,并且將合并后的allReducer傳遞給createStore函數作為第一個參數,目的是將這兩個組件的狀態用一個對象包裹起來,再傳給store。
5.Person組件已經與redux建立起了聯系,那么現在可以在Person組件中書寫Person的UI組件以及Person的容器組件(使用react-redux)。
import React, { Component } from 'react' import { nanoid } from 'nanoid' import { connect } from 'react-redux' import { createAddPersonAction } from '../../redux/actions/person' class Person extends Component { addPerson = () => { const name = this.nameNode.value const age = this.ageNode.value const personObj = { id: nanoid(), name, age } this.props.dispatchAddPerson(personObj) this.nameNode.value = '' this.ageNode.value = '' } render() { return ( <div> <h2>我是Person組件,上方組件求和為:{this.props.count}</h2> <input ref={currentNode => this.nameNode = currentNode} type="text" placeholder='輸入名字' /> <input ref={currentNode => this.ageNode = currentNode} type="text" placeholder='輸入年齡' /> <button onClick={this.addPerson}>添加</button> <ul> { this.props.personArr.map(personObj => { return <li key={personObj.id}>{personObj.name}---{personObj.age}</li> }) } </ul> </div> ) } } export default connect( state => ({ personArr: state.persons, count: state.count }), { dispatchAddPerson: createAddPersonAction } )(Person)
6.同時修改Count組件內容,使Count組件可以顯示Person組件的人數。
<h2>我是Count組件,下方組件總人數為:{this.props.person}</h2> // // export default connect( state => ({ count: state.count, person: state.persons.length }), { jia: createIncrementAction, jian: createDecrementAction, jiaAsync: createIncrementAsyncAction } )(Count)
注意:關于connect()()函數詳解內容,點擊:<react-redux>基本使用與優化
總結:
- 定義一個Person組件,和Count組件通過redux共享數據;
- 為Person組件編寫:reducer、action,配置constant常量;
- 重點:Person的reducer和Count的reducer要使用combineReducers進行合并,合并后的總狀態是一個對象;
- 交給store的是總reducer。
原文鏈接:https://blog.csdn.net/Svik_zy/article/details/126078947
相關推薦
- 2022-03-24 c++中的bind使用方法_C 語言
- 2022-03-24 C/C++實現蛇形矩陣的示例代碼_C 語言
- 2023-04-01 SqlServer字符截取的具體函數使用_MsSql
- 2022-11-21 深入了解Golang官方container/heap用法_Golang
- 2023-01-02 Python中字符串的常用方法總結_python
- 2023-03-27 Android數據結構優化教程_Android
- 2023-02-03 python關于excel多個sheet的導入導出方式_python
- 2023-07-04 JUC阻塞隊列BlockingQueue---LinkedBlockingQueue
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支