react-redux多個組件數(shù)據(jù)共享的方法

多個組件數(shù)據(jù)共享
我們之前講解的一直都是只有一個組件需要向redux讀取狀態(tài),也就是Count這個求和組件。那么我們在實際使用redux的場景中,當然是有很多組件一起共享數(shù)據(jù)才需要使用到redux進行狀態(tài)管理啦,現(xiàn)在我們就來看看多個組件通過redux實現(xiàn)數(shù)據(jù)共享的場景吧~
現(xiàn)在我們創(chuàng)建一個Person組件,同樣的,Person組件的數(shù)據(jù)也交給redux管理。此時,Count組件也可以從redux中讀取到Person組件的數(shù)據(jù),Person組件也可以從redux中讀取到Count組件之前存放在redux中的數(shù)據(jù)。是不是很方便呢?這就是redux集中式的狀態(tài)管理中的多個組件的數(shù)據(jù)共享。
項目結(jié)構(gòu):
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組件部分內(nèi)容已在前幾篇文章中,在本文中注重的是新增的Person組件與之前的Count組件共享狀態(tài)。
1.首先在constant.js中添加我們在Person組件中需要使用的類型:
export const INCREMENT = 'increment' export const DECREMENT = 'decrement' + export const ADD_PERSON = 'add_person'
該模塊是用于定義action對象中type類型的常量模塊,便于管理的同時避免程序員單詞拼寫出錯。
2.編寫Person組件的action文件,用于創(chuàng)建action動作對象以供Person組件使用:
/src/redux/actions/person.js
/*
該文件專門為Person組件生成action動作對象
*/
import { ADD_PERSON } from "../constant";
// 創(chuàng)建增加一個person的action動作對象
export const createAddPersonAction = personObj => ({ type: ADD_PERSON, data: personObj })
3.編寫Person組件的reducer文件,用于創(chuàng)建一個為Person組件服務的reducer函數(shù)
/src/redux/reducers/person.js
/*
1.該文件用于創(chuàng)建一個為Person組件服務的reducer函數(shù)
2.reducer函數(shù)會接收到兩個參數(shù),分別為之前的狀態(tài)(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內(nèi)部存儲的數(shù)據(jù)不需要任何的標識。但是store中若存放了多個組件的狀態(tài),那么就需要用一個對象將所有的狀態(tài)囊括起來,每個狀態(tài)都是一組key:value值。
比如,Count組件存儲的狀態(tài)為:count:0。Person組件存儲的狀態(tài)為: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組件的狀態(tài)數(shù)據(jù),現(xiàn)在新增了Person組件需要使用redux,那么就應該對store.js進行一些修改。
在store.js文件中,從redux中新引入combineReducers函數(shù)用于合并reducer;
引入為Person組件服務的reducer;
將原先的countReducer與新引入的personReducer合并,并且將合并后的allReducer傳遞給createStore函數(shù)作為第一個參數(shù),目的是將這兩個組件的狀態(tài)用一個對象包裹起來,再傳給store。
5.Person組件已經(jīng)與redux建立起了聯(lián)系,那么現(xiàn)在可以在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組件內(nèi)容,使Count組件可以顯示Person組件的人數(shù)。
<h2>我是Count組件,下方組件總?cè)藬?shù)為:{this.props.person}</h2>
//
//
export default connect(
state => ({ count: state.count, person: state.persons.length }),
{
jia: createIncrementAction,
jian: createDecrementAction,
jiaAsync: createIncrementAsyncAction
}
)(Count)
注意:關(guān)于connect()()函數(shù)詳解內(nèi)容,點擊:<react-redux>基本使用與優(yōu)化
總結(jié):
- 定義一個Person組件,和Count組件通過redux共享數(shù)據(jù);
- 為Person組件編寫:reducer、action,配置constant常量;
- 重點:Person的reducer和Count的reducer要使用combineReducers進行合并,合并后的總狀態(tài)是一個對象;
- 交給store的是總reducer。
到此這篇關(guān)于react-redux多個組件數(shù)據(jù)共享的方法的文章就介紹到這了,更多相關(guān)react-redux數(shù)據(jù)共享內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
React Refs轉(zhuǎn)發(fā)實現(xiàn)流程詳解
Refs是一個 獲取 DOM節(jié)點或React元素實例的工具,在React中Refs 提供了一種方式,允許用戶訪問DOM 節(jié)點或者在render方法中創(chuàng)建的React元素,這篇文章主要給大家介紹了關(guān)于React中refs的一些常見用法,需要的朋友可以參考下2022-12-12
TypeScript在React項目中的使用實踐總結(jié)
這篇文章主要介紹了TypeScript在React項目中的使用總結(jié),本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-04-04
基于React Context實現(xiàn)一個簡單的狀態(tài)管理的示例代碼
本文主要介紹了基于React Context實現(xiàn)一個簡單的狀態(tài)管理的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-07-07
React?createRef循環(huán)動態(tài)賦值ref問題
這篇文章主要介紹了React?createRef循環(huán)動態(tài)賦值ref問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-01-01

