【问题标题】:React-Apollo incoherent dataReact-Apollo 不连贯数据
【发布时间】:2017-02-23 05:44:54
【问题描述】:

我一直在用 React 尝试 Apollo,但目前遇到了问题。

我有一个产品属于多个类别的基本数据

query getProduct{
    product(id: 1){
        id
        name
        categories{id,name}
    }
}

正如预期的那样,这会返回类似的东西

{
  "data": {
    "p": {
      "id": 1,
      "name": "Samsung Galaxy S7",
      "categories": [
        {
          "name": "Phone"
        },
        {
          "name": "Samsung"
        }
      ]
    }
  }
}

这是我的反应组件

class TileProductComponent extends Component{

    constructor(...args){
        super(...args)
    }

    render(){
        if(this.props.data.loading)
            return <div>Loading...</div>

        var product = this.props.data.p

        console.log(this.props.data)

        return (
            <div> {product.name} </div>
        )
    }
}

var TileProduct = graphql(
    gql`
        query TestQuery($id: Int!){
            product(id: $id){
                id
                name
                categories{id,name}
            }
        }
    `,
    {
        options : {
            variables : {id:1}
        }
    }
)(TileProductComponent)

但是一旦它被传递到 react 组件中,我发现它是(来自 console.log(this.props.data))

    "product": {
      "id": 1,
      "name": "Phone",
      "categories": [
        {
          "name": "Phone"
        },
        {
          "name": "Samsung"
        }
      ]
    }

产品名称不知何故采用第一类名称?我猜id也会。一种解决方法是更改​​模式中的字段名称,但在我看来,它不应该真的这样做。

这是一个已知问题还是只有我一个人遇到此问题?任何建议的解决方案?

【问题讨论】:

  • 您定义了dataIdFromObject 吗?听起来您的产品和类别可能有重叠的 ID,这导致 Apollo 认为它们是同一个对象。你能插入你的 Apollo 客户端初始化代码吗?
  • var netfworkInterface = createNetworkInterface('localhost:3030/graphql') this.client = new ApolloClient({ netfworkInterface, dataIdFromObject: r => r.id })
  • 所以我想我必须为不同的“集合”返回不同的结果,例如我可以为产品做“product.”+r.id 等等,但我怎么知道哪个它来自的集合,因为我只有文档本身

标签: graphql apollo apollostack


【解决方案1】:

问题在于您的dataIdFromObject 函数。此函数需要为来自服务器的不同对象返回一个唯一值。一种简单的方法是将 GraphQL 中内置的 __typename 字段与您的 ID 字段一起使用。这是一个代码sn-p:

const client = new ApolloClient({
  queryTransformer: addTypename,
  dataIdFromObject: (result) => {
    if (result.id && result.__typename) {
      return result.__typename + result.id;
    }
    return null;
  }
});

要查看它在应用上下文中的使用情况,请查看 GitHunt 前端示例,该示例使用 SQL 增量 ID:https://github.com/apollostack/GitHunt-React/blob/380bedaef97f2a0932c1ab33bd964812d4a8a65e/ui/client.js#L42-L48

【讨论】:

  • 非常感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2017-03-10
  • 2019-12-29
  • 1970-01-01
  • 2011-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-07
相关资源
最近更新 更多