React Apollo和Redux:将自定义化简器与Apollo状态结合使用 [英] React Apollo and Redux: Combine custom reducers with Apollo state

查看:65
本文介绍了React Apollo和Redux:将自定义化简器与Apollo状态结合使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Redux中使用 react-apollo 时,来自服务器的数据将在 apollo 键下缓存在redux存储中:

When using react-apollo with redux, data from the server is cached in the redux store under an apollo key:

{
    apollo: // results from Apollo queries
}

在创建了自己的reducers和相应的状态树之后,您的商店可能看起来像这样:

After creating your own reducers and corresponding state tree, your store might look like this:

{
    apollo: { ... },
    ui: {
        selectedItem: 2;
        showItems: 6
    }
}

想象一下,有一个动作会更改 ui.selectedItem 的值,并且该值是埋在 apollo 对象中某处的项的索引.

Imagine that there is an action which changes the value of ui.selectedItem, and that this value is the index of an item buried somewhere in the apollo object.

使用减速器组成,我们的 ui的减速器状态在Apollo状态下将无权访问任何东西.

With reducer composition, reducers for our ui state will rightly have no access to anything under the Apollo state.

在我们的组件中,我们可以通过 mapStateToProps 订阅 ui 状态的更改,并可以使用 react-apollo 将Apollo结果映射到道具code> GraphQL容器(或 @graphql 装饰器).

In our component we can subscribe to changes on our ui state via mapStateToProps, and we can map Apollo results to props using the react-apollo GraphQL container (or @graphql decorator).

但是我们如何使用根据Apollo结果和应用程序中其他状态计算出的值来更新商店?

But how can we update our store with values that are computed from Apollo results and other state in our application?

例如,如果 apollo.item.list 是项数组,而 ui.selectedItem 是您要在该列表中定位的索引-怎么可能存储包含以下值:

For example, if apollo.item.list is an array of items, and ui.selectedItem is the index you want to target in that list - how could the store contain a value for:

apollo.item.list[ui.selectedItem]

推荐答案

我的解决方案是使用重构通过 mapProps 组成存储状态和阿波罗状态:

My solution was to use recompose to compose the store and Apollo states together via mapProps:

import { mapProps, compose } from ‘recompose’;

const mapStateToProps = state => ({
  selectedItem: state.ui.selectedItem
})

const mapDataToProps = {
  props: ({ data }) => ({ list: data.item.list })
}

const selectProps = mapProps(({ selectedItem, list}) => ({
  item: list[selectedItem] 
}))

export default compose(
  connect(mapStateToProps, {}),
  graphql(MY_QUERY, mapDataToProps),
  selectProps
)(MyComponent);

这还允许我们使用graphql 加载状态rel ="nofollow noreferrer">分支,因此在数据可用之前,我们不会运行 selectProps .

This also allows us to check the graphql loading state using branch, so we don't run selectProps until the data is available.

感谢 Daniel Rearden的回答为我指明了正确的方向.

Thanks to Daniel Rearden's answer for pointing me in the right direction.

这篇关于React Apollo和Redux:将自定义化简器与Apollo状态结合使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆