【发布时间】:2018-11-10 13:13:21
【问题描述】:
我正在尝试找到在 componentDidMount 内的映射项目上使用 setState 的解决方案。
我正在使用 GraphQL 和 Gatsby 并返回许多 data 项目,但要求特定的 pathname 是 === 到 slug state 在组件中更新为匹配的 @ 987654330@.
propertyInit = () => {
const pathname = location.pathname;
return (
<StaticQuery
query={graphql`
query {
allContentfulProperties {
edges {
node {
id
slug
information {
littleHotelierId
}
}
}
}
}
`}
render={data => {
data.allContentfulProperties.edges.map(({ node: property }) => {
if (pathname === property.slug) {
!this.isCancelled &&
this.setState({
littleHotelierId: property.information.littleHotelierId
});
}
return null;
});
}}
/>
);
};
然后我将其拉入componentDidMount
componentDidMount() {
this.propertyInit();
}
不相关,但作为参考 this.isCancelled = true; 添加到 componentWillUnmount。
我没有收到任何错误,但如果我 console.log(littleHotelierId) 我什么也得不到。
起初我确实认为这可能是因为 return 为 null 所以尝试给 map 一个 const 并返回为
render={data => {
data.allContentfulProperties.edges.map(({ node: property }) => {
if (pathname === property.slug) {
const littleHotelier =
!this.isCancelled &&
this.setState({
littleHotelierId: property.information.littleHotelierId
});
return littleHotelier;
}
});
}}
但这也失败了。
目标是 componentDidMount 将 GraphQL data 中返回的项目映射为
componentDidMount() {
if (path1 === '/path-slug1') {
!this.isCancelled &&
this.setState({
littleHotelierId: 'path-id-1'
});
}
if (path2 === '/path-slug2') {
!this.isCancelled &&
this.setState({
littleHotelierId: 'path-id-2'
});
}
... // other items
}
我认为问题在于 GraphQL 以异步方式获取数据,并且此请求未完成,因为 componentDidMount() 被调用。如果我console.log data 它不会向console 返回任何内容。我该如何解决这个问题?
【问题讨论】:
标签: javascript reactjs graphql gatsby