【问题标题】:Apollo fetchMore updated props not re-rendering componentApollo fetchMore 更新的 props 不重新渲染组件
【发布时间】:2017-08-30 00:32:46
【问题描述】:

我有一个来自 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);

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

【问题讨论】:

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


【解决方案1】:

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

你基本上可以做到

this.setState({

posts: [old values + new values],

})

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

【讨论】:

  • 新的 props 应该由graphql 高阶组件传入,触发重新渲染。
猜你喜欢
  • 2020-03-27
  • 2016-12-30
  • 1970-01-01
  • 2019-08-09
  • 2020-10-18
  • 2022-07-21
  • 1970-01-01
  • 2021-04-26
  • 2021-02-03
相关资源
最近更新 更多