1

我有一个react组件,它显示您附近的兴趣点的地图。

我的 HOC 用于react-apollo查询这些兴趣点并将数据作为道具提供给纯 UI 组件。

我正在尝试将用户的位置从navigator.geolocation我的 graphql 查询的变量中获取。但由于导航器 API 是异步的,我似乎无法让它工作。

它看起来像这样:

const getCurrentPosition = async (settings = {}) =>
  new Promise((resolve, reject) => {
    navigator.geolocation.getCurrentPosition(resolve, reject, settings);
  }
);

const query = gql`
  query($coordinates: [[Float]]){
    whatever(filter: {coordinates: $coordinates}) {
      _id
      coordinates
    }
  }
`;

const withData = graphql(query, {
  options: async (props) => {
    const position = await getCurrentPosition();

    return {
      variables: {
        coordinates: [position.coords.latitude, position.coords.longitude],
      },
    };
  },
  props: ({ data: { loading, whatever, refetch, variables: { coordinates } } }) => ({
    loading,
    whatever,
    coordinates,
    refetch,
  }),
});


const List = ({ loading, whatever, coordinates, refetch }) => {
  if (loading) {
    return null;
  }
  return (/* map display*/);
};

List.propTypes = {
  loading: React.PropTypes.bool.isRequired,
  whatever: React.PropTypes.array,
  coordinates: React.PropTypes.array,
  refetch: React.PropTypes.func,
};

export default withData(Map);

coordinates始终null在我的组件内。

当我记录事情时,似乎计算了位置,但 graphql 查询和组件渲染发生在它之前。

当我们获取用户位置时,不会调用查询并且不会重新渲染组件。

可能吗 ?难道我做错了什么?

4

1 回答 1

2

我会事先进行异步调用并通过道具注入它,然后如果位置不在这里,则使用http://dev.apollodata.com/react/api.html#graphql-config.skip跳过查询。

也许使用 recompose/withProps 等?

于 2017-03-23T13:22:08.523 回答