reactjs - Apollo fetchMore 更新的 props 不重新渲染组件

标签 reactjs react-native apollo react-apollo apollo-client

我有一个来自 graphql 查询的“帖子”数组,我正在尝试使用偏移+限制进行分页,如 apollo docs 中所述。 。当前按“loadMore”会更新查询,并且 fetchMoreResult 中的结果是正确的。此外,连接的 newResults 在记录时正确显示。也许我做出了错误的假设,但我理解文档的方式是新生成的 posts 将自动传递到我的 TestComponent 并重新渲染。这是不正确的吗?

import React from 'react';
import { View, Text } from 'react-native';
import { graphql } from 'react-apollo';
import { GetPosts } from 'app/graphql';

class TestComponent extends React.Component {
  render() {
    // I would expect this to log the new props after press "loadMore"
    console.log(this.props)
    return (
      <View style={{marginTop: 40}}>
        <Text onPress={this.props.loadMore}>Push me</Text>
      </View>
    )
  }
}

export default graphql(GetPosts, {
  options: () => ({
    variables: {
      offset: 0,
      limit: 1
    }
  }),
  props: ({ ownProps, data }) => {
    return {
      ...ownProps,
      posts: data.posts,
      loadMore: () => {
        return data.fetchMore({
          variables: {
            offset: 1,
            limit: 1
          },
          updateQuery: (previousResult, { fetchMoreResult }) => {            
            if (!fetchMoreResult) {
              return previousResult;
            }
            const newResult = Object.assign({}, previousResult, {
              posts: [...previousResult.posts, ...fetchMoreResult.posts]
            });
            console.log(newResult);
            return newResult;
          },
        })
      }
    };
  }
})(TestComponent);

编辑 (4/11/17) 我未能解释我的查询 GetPosts 包含联合类型,这似乎可能是问题所在,因为如果我删除它们,更新将按预期工作。我已经提出了一个关于包的问题,​​希望能更清楚:https://github.com/apollographql/react-apollo/issues/602

最佳答案

为了重新渲染 TestComponent,您必须更改组件的状态。

你基本上可以做到

this.setState({

posts: [old values + new values],

})

然后在渲染函数中,您可以通过 this.state.posts 调用它

关于reactjs - Apollo fetchMore 更新的 props 不重新渲染组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43213482/

相关文章:

javascript - React 中部分但不是全部获取数据未定义

javascript - ReactJS 无法加载 src 中的文件

react-native - Mobx @compute函数与参数

javascript - GraphQL + Apollo 错误 : Uncaught (in promise)

graphql - 如何使用 Apollo GraphQL 查询结果作为另一个查询的输入?又名 : request chaining

javascript - 不能在 React Native 中只调用一次函数?

reactjs - 找不到模块 '@babel/plugin-transform-runtime' 从

javascript - 当我的组件卸载时,如何删除 Canvas 元素?

ios - React Native WebView 在 iOS 上缺少 session cookie

reactjs - 区域更改后无法触摸 React Native Maps 自定义标记