[英]having multiple instance of same reusable redux react components on the same page/route
我們正在創建一個大型前端應用程序。
我們正在使用 React-Redux
我們正在創建一些可重用的組件。
這個問題是關於在同一頁面/路由上有多個相同可重用 redux react 組件的實例
我們有一個Sectionheader
組件。 這綁定到 redux 狀態。
它偵聽標題屬性 reducer SectionheaderReducer
。
由於我們在頁面上有 2 個此Sectionheader
實例, Sectionheader
都傾向於顯示相同的值,因為它們綁定到相同的商店狀態屬性。
如何使基於 redux 的可重用 React 組件可配置? 這樣每個實例都可以為 reducer SectionheaderReducer
具有不同的 header 屬性值
您需要實現某種命名空間實例的方法。 這可以像傳入一個鍵來區分組件和減速器一樣基本。
您可以在mapStateToProps
函數中使用ownProps
來引導映射到命名空間
const mapStateToProps = (state, ownProps) {
let myState = state[ownProps.namespace]
return {
myState.value
}
}
可以使用相同的方法將命名空間傳遞給mapDispatchToProps
const mapDispatchToProps = (dispatch, ownProps) {
return {
myAction: (myParam) => dispatch(myAction(ownProps.namespace, myParam))
}
}
只要記住在動作類型中使用命名空間,這樣減速器就不會踩到腳趾
const myAction => (namespace, myParam) {
return { type: `${namespace}/${MY_TYPE_CONSTANT}`, myParam }
}
並確保減速器也有命名空間
const myReducer = (namespace) => (state = initialState, action) => {
switch(action.type) {
case `${namespace}/${MY_TYPE_CONSTANT}`:
return { ...state, action.myParam }
default:
return state
{
}
現在在組合減速器時添加 2 個命名空間減速器
combineReducers({
myInstance1 : myReducer('myInstance1')
myInstance2 : myReducer('myInstance2')
}
最后將命名空間傳遞給每個實例
render() {
return (
<div>
<MyComponent namespace='myInstance1' />
<MyComponent namespace='myInstance2' />
</div>
)
}
免責聲明:我是以下庫的主要貢獻者。
redux-subspace可以提供更高級的命名空間實現,而無需為每個想要擁有多個實例的組件重新實現此模式。
創建減速器與上面類似
const reducer = combineReducers({
myInstance1: namespaced('myInstance1')(myReducer)
myInstance2: namespaced('myInstance2')(myReducer)
})
然后可以使用SubspaceProvider
來切換每個組件的狀態
render() {
return (
<div>
<SubspaceProvider mapState={state => state.myInstance1} namespace='myInstance1'>
<MyComponent />
</SubspaceProvider>
<SubspaceProvider mapState={state => state.myInstance2} namespace='myInstance2'>
<MyComponent />
</SubspaceProvider>
</div>
)
}
只需確保您還將mapStateToProps
函數更改為從提供程序中映射的子樹開始遍歷
const mapStateToProps = (state) {
return {
state.value
}
}
如果您希望減少嵌套,還有一個高階組件。
我以不同的方式實現了它,實際上沒有使用命名空間更改操作名稱。
相反,我添加了 infra 函數,它將攔截動作創建者並向每個動作添加meta-data
。 (遵循FSA
)這樣您就不需要更改減速器或mapStateToProps
函數。
它也與redux-thunk
兼容。
應該很容易使用... reducer-action-interceptor
我將這個問題解釋為:
<SectionHeader />
)一種可能的解決方案是讓您將“部分”的想法添加到您的商店。 您將創建管理數據內容結構的 reducer。 EG store 狀態有時可能如下所示:
{
sections: {
0: {
header: 'My section title',
content: 'Whatever your content is'
},
1: {
header: 'My other section title',
content: 'Loads of lovely writing or hrefs to images or whatever'
}
}
}
``
然后,您將擁有一個“容器組件”或“布局組件”或“智能組件”(它們有很多名稱),它們“知道”您要在特定頁面上使用第 2 部分和第 4 部分。 它如何知道這一點,取決於您。 也許您對索引進行了硬編碼(因為它總是相同的),也許您有一個過濾規則,也許您在商店中有另一個定義選擇的字段......等等。
然后容器組件會將選擇的標題傳遞給 "dumb" ,可能是這樣的:
<SectionHeader>{sections[2].header}</SectionHeader>
或者
<SectionHeader title={sections[2].header} />
將我們的組件轉換為啞(無狀態)組件,以便這些組件可以輕松重用而不會出現任何復雜情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.