当页面加载时,我使用 componentDidMount() document.createElement("script");
在布局中index.js
ReactJS 和 GatsbyJS 项目的
componentDidMount () {
const tripadvisorLeft = document.createElement("script");
tripadvisorLeft.src = "https://www.jscache.com/wejs?wtype=selfserveprop&uniq=789&locationId=10467767&lang=en_NZ&rating=true&nreviews=0&writereviewlink=true&popIdx=true&iswide=true&border=false&display_version=2";
tripadvisorLeft.async = true;
document.body.appendChild(tripadvisorLeft);
}
然后请求显示数据并且工作正常。然而,当我 <link to=...
另一个页面使用 gatsby-link
(想象一下同样的问题适用于 react-router
), componentDidMount()
已经运行,因此不会再次获取数据。
如何确保此脚本是 mounted
每次之后 path
更改,或者通过特定的 path
更好?
最佳答案
您可以使用navigateTo
从 gatsby-link
包中滚动您自己的 Link
组件,该组件在导航之前执行您的自定义逻辑。
Link.jsx
import React from "react";
import { navigateTo } from "gatsby-link";
const RESOURCE_PATH = "https://www.jscache.com/wejs?wtype=selfserveprop&uniq=789&locationId=10467767&lang=en_NZ&rating=true&nreviews=0&writereviewlink=true&popIdx=true&iswide=true&border=false&display_version=2";
const refetchAndNavigate = (path) => () => {
// refetch
const tripadvisorLeft = document.createElement("script");
tripadvisorLeft.src = RESOURCE_PATH;
tripadvisorLeft.async = true;
document.body.appendChild(tripadvisorLeft);
// finally navigate
navigateTo(path);
}
const Link = ({ to, ...propsToPass }) => (
<div {...propsToPass} onClick={refetchAndNavigate(to)}/>
);
export default Link;
我还没有测试过这段代码,但想法可以工作。
关于javascript - 通过path.name重新挂载componentDidMount(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49893481/