【发布时间】:2018-10-16 19:02:08
【问题描述】:
我正在尝试从gatsby-browser.js (gatsby browser API) 在replaceRouterComponent 中运行 GraphQL 查询。而我可以从 Contentful 访问数据。
这可能不是最好的解决方案,任何关于我如何以其他方式实现的建议也将不胜感激。
这是问题 -
组件内部 TripAdvisor.js 我将脚本安装在 componentDidMount 中,而 locationId 是基于从 posts 创建的个人 this.props.tripAdvisorId 中提取的数据内容丰富。每个post(属性)都有一个单独的locationId,在脚本中更改src 时会显示相关的评论。
componentDidMount () {
const tripadvisorLeft = document.createElement("script");
tripadvisorLeft.src = "https://www.jscache.com/wejs?wtype=selfserveprop&uniq=789&locationId=" + this.props.tripAdvisorId + "&lang=en_AU&rating=true&nreviews=0&writereviewlink=true&popIdx=true&iswide=true&border=false&display_version=2";
tripadvisorLeft.async = true;
document.body.appendChild(tripadvisorLeft);
const tripadvisorRight = document.createElement("script");
tripadvisorRight.src = "https://www.jscache.com/wejs?wtype=selfserveprop&uniq=998&locationId=" + this.props.tripAdvisorId + "&lang=en_AU&rating=false&nreviews=4&writereviewlink=false&popIdx=false&iswide=true&border=false&display_version=2";
tripadvisorRight.async = true;
document.body.appendChild(tripadvisorRight);
}
我在页面级别的componentDidMount 内还有一个函数,用于重写上面 TripAdvisor 脚本中的数据。 TripAdvisor 脚本会创建一个名为 injectselfserveprop*** 的函数(其中 *** 是随机数)。没有这个,当到达带有Link 的组件时,函数不会被调用
/templates/properties/reviews.js
componentDidMount() {
Object.keys(window).forEach((key) => {
if (key.match(/^injectselfserveprop[0-9]+$/)) {
window[key]();
}
});
}
在 /templates/properties/reviews.js 的同一文件中,我使用 shouldComponentUpdate 到 return false,因为它会阻止 TripAdvisor 在页面之间不断更新(使用link
shouldComponentUpdate() {
return false;
}
现在,这个解决方案的失败之处在于更改脚本src 的locationId。如果我不需要根据post 更改locationId,它工作得非常好。
当 link 到另一个 post 与另一个 locationId 并且评论组件未更新时,它会失败。但是,然后 link 离开并返回新评论。
您可以在here 看到这种情况并按照以下步骤操作 -
- 点击link 并向下滚动查看与 Chatelaine 相关的评论
- 然后在菜单中 > 选择 Varenna > 在水平菜单中选择评论,您仍然会看到 Chatelaine 评论。
- 现在,单击水平菜单中的 > 位置 > 然后再次单击评论 > 您将获得正确的评论并计入 Varenna。
有一个完整站点here 的 GitHub 存储库。要查找的两个文件位于/src/templates/properties/reviews.js 和src/components/properties/TripAdvisor.js
现在我已经概述了我的问题,我相信最好的解决方案是在 gatsby-browser.js 内将 TripAdvisor 脚本包装在 replaceRouterComponent 中,并使用条件语句仅适用于通过 Link 直接访问 reviews.js 的页面。
但是,我找不到使用 gatsby-browser.js (gatsby browser API) 中的 tripAdvisorID 数据的解决方案。而我可以使用 GraphQL 从 Contentful 访问数据。
如果您有其他解决方案,请告诉我。
【问题讨论】:
标签: javascript reactjs react-router graphql gatsby