javascript - 通过path.name重新挂载componentDidMount()

标签 javascript reactjs react-router gatsby

当页面加载时,我使用 componentDidMount() document.createElement("script");在布局中index.js ReactJSGatsbyJS 项目的

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 更好?

最佳答案

您可以使用navigateTogatsby-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/

相关文章:

javascript - 使用连字符命名 React 组件 props

javascript - 使用 css 和 jquery 制作圆形动画

reactjs - 使用 Hook 无法查看方法辅助函数内的状态

javascript - 组件的高阶函数过滤方法

react-router - 如何在 react-router v5 中监听查询参数更改事件

javascript - Vuejs组件路由动态选择

javascript - 来自 Angular 应用程序的全局回调

reactjs - 如何在 React Router v4 中嵌套路由?

javascript - 付款成功后跳转至仪表板

javascript - 使用表情符号 react 加入用户语音 channel