【发布时间】:2018-06-17 16:58:34
【问题描述】:
我有一个 React 应用,它使用 Redux 进行一些应用内状态管理,并使用 Apollo 从服务器获取数据。在我的网络选项卡中,我的 graphql 查询成功并且响应是我所期望的,但是当我尝试在 React 组件的 componentDidMount 生命周期中引用数据时,数据不存在并且加载状态为“真”。
如果我将代码移动到不同的生命周期函数,例如 render(),数据确实会出现,但我需要它在 componentDidMount 中工作。我是阿波罗的新手。
import React, { Component } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import SdkMap from "@boundlessgeo/sdk/components/map";
import SdkZoomControl from "@boundlessgeo/sdk/components/map/zoom-control";
import * as mapActions from "@boundlessgeo/sdk/actions/map";
import { graphql } from "react-apollo";
import gql from "graphql-tag";
function mapStateToProps(state) {
return {
map: state.map
};
}
class Map extends Component {
static contextTypes = {
store: PropTypes.object.isRequired
};
componentDidMount() {
const store = this.context.store;
store.dispatch(mapActions.setView([-95.7129, 37.0902], 3));
/* ADD SITES LAYER */
store.dispatch(
mapActions.addSource("sites_src", {
type: "geojson",
data: {
type: "FeatureCollection",
features: []
}
})
);
store.dispatch(
mapActions.addLayer({
id: "sites",
source: "sites_src",
type: "circle",
paint: {
"circle-radius": 3,
"circle-color": "blue",
"circle-stroke-color": "white"
}
})
);
console.log(this.props.data); //response doesn't include query fields
if (this.props.data.allSites) {
let sites = this.props.data.allSites.edges;
for (let i = 0; i < sites.length; i++) {
let site = sites[i].node;
let geojson = site.geojson;
if (geojson) {
console.log(site);
const feature = {
type: "Feature",
geometry: geojson,
properties: {
id: site.id
}
};
store.dispatch(mapActions.addFeatures("sites_src", feature));
}
}
}
}
render() {
const store = this.context.store;
return (
<SdkMap store={store} >
<SdkZoomControl />
</SdkMap>
);
}
}
const query = graphql(
gql`
query {
allSites {
edges {
node {
id
projectId
location
areaAcres
geojson
}
}
}
}
`
);
const MapWithRedux = connect(mapStateToProps)(Map);
const MapWithApollo = query(MapWithRedux);
export default MapWithApollo;
【问题讨论】:
标签: reactjs apollo react-apollo