我正在尝试将嵌套对象写入阿波罗缓存,但它无法正常工作。简单的变量写工作正常。我正在使用Apollo-client v2.4



// Schema
const GET_DATA_FROM_CACHE = gql `
  name
  address
  age
`
// Reading data from cache
  render() {
    return (
    <Query query = {GET_DATA_FROM_CACHE} fetchPolicy = {"cache-only"}>
      {({ data }) => (
        <View >
          <Text> Name: {data.name} </Text>
        </View>
      )}
    </Query>
   )
  }





// THIS WORKS as I can see the name in my Text field




client.writeData({
  data: {
    name: 'mr x',
    age: 25
  }
})





// THROWS ERROR: "cannot read property country of undefined"




client.writeData({
  data: {
    name: 'mr x',
    address: {
      country: 'y',
      city: 'z'
    },
    age: 25
  }
})

最佳答案

我遇到了这个问题,并通过确保在嵌套对象中包含具有适当值的__typename字段来解决了该问题。例如:

client.writeData({
  data: {
    name: 'mr x',
    address: {
      id: 1,
      country: 'y',
      city: 'z',
      __typename: "Address"
    },
    age: 25
  }
})


我还要补充一点,包括一个“ id”字段是个好主意(除非您已配置getIdFromObject选项)。在Apollo的Cache Normalization section中有更多信息。

作为参考,我得到的错误是:


  不变违规:存储错误:应用程序尝试写入
  没有提供ID的对象,但商店已包含ID
  {Typename}:{id}此对象。

09-20 14:54