React Apollo 和 Redux:将自定义减速器与 Apollo 状态相结合 [英] React Apollo and Redux: Combine custom reducers with Apollo state

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

问题描述

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

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
}

在创建您自己的 reducer 和相应的状态树后,您的商店可能如下所示:

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.

使用 reducer 组合,我们的 ui 的 reducer 状态将无法访问 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 结果映射到 propscode> 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]

推荐答案

我的解决方案是使用 recompose 通过 mapProps 将 store 和 Apollo 状态一起compose:

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">branch,所以在数据可用之前我们不会运行 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天全站免登陆