2

在 redux 应用程序中,使用 connect 从 state 中获取数据是要走的路。问题是我发现自己将组件与状态原子紧密耦合。如果我想更改状态树的结构,所有用于消耗这种状态的组件都会中断。

那么如何将它们解耦呢?

例子

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(){
let my_posts = Posts.ofUser(currentUser.id)
//now Posts should be a service that has access to state and return the needed data.
}

我如何创建这样的对象来处理状态并公开组件和连接函数联系以获取信息的 api。

我读了很多关于重新选择的内容,但是如何实现呢?

4

1 回答 1

0

将状态形状与组件分离的最简单方法是通过选择器查询任何状态道具。

它添加了一些样板代码,但一旦完成,您将在组件和应用程序状态之间建立一个完全可测试的桥梁。

要开始使用选择器,请查看 Redux Docs Computing 派生数据页面。

Reselect 只是一个创建记忆选择器的实用程序。

于 2017-04-28T13:38:59.130 回答