2

我在我的应用程序中使用 Relay Modern 并使用该requestSubscription功能成功集成了订阅。一切正常updater,我用来更新缓存的函数会通过正确的订阅有效负载正确调用。

订阅用于将新项目添加到Link元素列表中。这是订阅的样子:

NewLinkSubscription.js

const newLinkSubscription = graphql`
  subscription NewLinkSubscription {
    Link {
      mutation
      node {
        id
        description
        url
        createdAt
        postedBy {
          id
          name
        }
      }
    }
  }
`

export default (updater, onError) => {

  const subscriptionConfig = {
    subscription: newLinkSubscription,
    variables: {},
    updater,
    onError
  }

  requestSubscription(
    environment,
    subscriptionConfig
  )

}

然后我有一个LinkList渲染所有Link元素的组件。在componentDidMount该组件中,我启动NewLinkSubscription

链接列表.js

class LinkList extends Component {

  componentDidMount() {
    NewLinkSubscription(
      proxyStore => {
        const createLinkField = proxyStore.getRootField('Link')
        const newLink = createLinkField.getLinkedRecord('node')
        const viewerProxy = proxyStore.get(this.props.viewer.id)
        const connection = ConnectionHandler.getConnection(viewerProxy, 'LinkList_allLinks')
        if (connection) {
          ConnectionHandler.insertEdgeAfter(connection, newLink)
        }
      },
      error => console.log(`An error occured:`, error),
    )
  }

  render() {
    console.log(`LinkList - render `, this.props.viewer.allLinks.edges)
    return (
      <div>
        {this.props.viewer.allLinks.edges.map(({node}) =>
          {
            console.log(`render node: `, node)
            return <Link key={node.id} link={node} viewer={this.props.viewer} />
          }
        )}
      </div>
    )
  }

}

export default createFragmentContainer(LinkList, graphql`
  fragment LinkList_viewer on Viewer {
    id
    ...Link_viewer
    allLinks(last: 100, orderBy: createdAt_DESC) @connection(key: "LinkList_allLinks", filters: []) {
      edges {
        node {
          ...Link_link
        }
      }
    }
  }
`)

现在,当带有新订阅的订阅Link进来时会发生这种情况。updater正确调用,并且似乎新节点正确插入到连接中(至少ConnectionHandler.insertEdgeAfter(connection, newLink)被调用)。

这会触发组件的重新渲染。当我调试render检查数据(props.viewer.allLinks.edges然而,问题是这个新节点实际上undefined是导致应用程序崩溃的原因!

图片

有人发现我在这里缺少什么吗?

4

1 回答 1

2

我能够让它工作,这就是我updater现在实现的方式:

NewLinkSubscription(
  proxyStore => {
    const linkField = proxyStore.getRootField('Link')
    const newLink = linkField.getLinkedRecord('node')
    const viewerProxy = proxyStore.get(this.props.viewer.id)
    const connection = ConnectionHandler.getConnection(viewerProxy, 'LinkList_allLinks', {
      last: 100,
      orderBy: 'createdAt_DESC'
    })
    if (connection) {
      const edge = ConnectionHandler.createEdge(proxyStore, connection, newLink, 'allLinks')
      ConnectionHandler.insertEdgeBefore(connection, edge)
    }
  },
  error => console.log(`An error occurred:`, error),
)
于 2017-06-29T19:16:57.643 回答