与React一起使用时进行阿波罗重读

时间:2018-10-09 11:11:49

标签: reactjs graphql apollo react-apollo

我们正在使用Apollo开发完整的第一个应用程序,在将它与react-router一起使用时遇到问题。

我们正在使用新组件,问题是当我们更改应用程序的路由时,它将使用最初获取的数据(即使服务器上的数据已更改)也是如此:

import React from 'react';
import { Query } from 'react-apollo';

import { GET_FAVORITE_JOBS } from './graphql';
import FavoriteJobList from './stateless';

export default () => (
  <div>
    <Query query={GET_FAVORITE_JOBS}>
      {({ loading, error, data }) => (
        <FavoriteJobList loading={loading} error={error} data={data} />
      )}
    </Query>
  </div>
);

我已经看到了:https://www.apollographql.com/docs/react/essentials/queries.html#refetching

我们必须在refetch上使用componentDidMount吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

所以您有两种可能性:

  

1,为查询定义一些随机输入,并将其传递给。

export default () => (
  <div>
    <Query query={GET_FAVORITE_JOBS} variables={{ random: New Date().getTime() }}>
      {({ loading, error, data }) => (
        <FavoriteJobList loading={loading} error={error} data={data} />
      )}
    </Query>
  </div>
);
  

2,导出为容器并将结果作为道具:

import { graphql } from "react-apollo";

const SomeComp = (props) => (
  <div>
    // You can acces the results here as props. 
    // Also You can use props.refetch() as an action or component lifecycles
  </div>
);
export default graphql(GET_FAVORITE_JOBS, {
  name: "getFavJobs",
  options: (props)=> ({
    variables: {
      random: New Date().getTime()
    }
  })
})(SomeComp));