簡體   English   中英

在React Redux中如何構建應用以將組件與狀態原子分離

[英]in react Redux how to structure app to decouple component from state atom

在redux應用程序中,使用connect從狀態獲取數據是一種方法。 問題是我發現自己將組件與狀態原子緊密地耦合在一起。 萬一我想改變狀態樹的結構,所有用來消耗這種狀態的組件都會損壞。

那么如何解耦呢?

initialState = {
 users: { ids:[1,2] , byId:{1:{name:'user 1'},2:{name:'user 2'} }
 posts: { ids:[1,2] , byId:{1:{title:'post 1'},2:{title:'post 1'} }
 access : {1:[1,2],2:[1,2]} //post_id : [user_id who can see post]
}

在這種簡單狀態下,我描述我有2個用戶和2個帖子,兩個帖子對兩個用戶都是可見的。

在列出帖子和用戶的組件中,連接可以是

render(){
let {posts,access,currentUser} = this.props;

let my_posts = posts.ids.map(post_id=>posts.byId[post_id])
                    .filter(post=>(access[post.id].indexOf(currentUser.id)>-1)
//above map will return posts, and filter will filterout posts user dont have access to.
}

connect( (state,prop)=>{currentUser:users[prop.user_id],posts,access})(Component);

<Component user_id={1} />

這里的問題是組件的render函數會對狀態進行很多操作以渲染正確的數據。 如果我能做些更好的話

render(){
let my_posts = Posts.ofUser(currentUser.id)
//now Posts should be a service that has access to state and return the needed data.
}

我如何創建處理狀態的Object並公開一個api,該api用於組件和連接函數聯系以獲取信息。

我讀了很多關於重新選擇的信息,但是如何實現呢?

使狀態形狀與組件分離的最簡單方法是通過選擇器查詢任何狀態道具。

它增加了一些樣板代碼,但是一旦完成,您將在組件和應用程序狀態之間建立一個完全可測試的橋梁。

要開始使用選擇器,請查看Redux Docs Computing派生數據頁面。

重新選擇只是一個用於創建記憶選擇器的實用程序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM