componentDidMount 是否会导致 html.script 消失?



我在将外部脚本安装到我的 React/Gatsby 应用程序的组件中时遇到问题。下面的脚本被调用到一个组件中,该组件在整个应用中的两个位置使用。

首先是pages/index.js并加载正常,零问题,但是当从模板调用在gatsby创建的页面(exports.createPages = ({ graphql, boundActionCreators }) => {)中使用时,脚本将加载,显示内容,然后继续。

下面是将脚本挂载到组件中的代码 -

componentDidMount () {
const tripadvisor = 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(tripadvisor);
}

我没有从控制台收到任何错误。

注意:与错误有关吗?我还在处理navigation元素bodyclass/layout/index.js文件中使用componentDidMountcomponentWillUnmount编写了此代码。

componentDidMount () {
this.timeoutId = setTimeout(() => {
this.setState({loading: ''});
}, 100);
this.innerContainer.addEventListener("scroll", this.handleHeaderStuck), 100;
this.innerContainer.addEventListener("scroll", this.handleSubNavStuck), 200;
}
componentWillUnmount () {
if (this.timeoutId) {
clearTimeout(this.timeoutId);
}
this.innerContainer.removeEventListener("scroll", this.handleHeaderStuck);
this.innerContainer.removeEventListener("scroll", this.handleSubNavStuck);
} 

更新:所有代码

import React from 'react';
import Link from 'gatsby-link'
import styled from 'styled-components'
const Wrapper = styled.section`
display:block;
`
class ReviewsPage extends React.Component {
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);
}
render() {           
return (
<Wrapper id="tripAdvisor">
<div id="TA_selfserveprop789" className="TA_selfserveprop">
<ul id="3LacWzULQY9" className="TA_links 2JjshLk6wRNW">
<li id="odY7zRWG5" className="QzealNl"></li>
</ul>
</div>
</Wrapper>
)
}
}
export default ReviewsPage

因此,您的componentDidMount()所做的只是添加一个引用第三方脚本的<script>标签。 我假设第三方脚本试图向 DOM 添加一些信息或内容(您可以直观地看到的东西)。

但是,DOM 只存在于组件更新之间。 React 会在检测到 State 或 Props 的更改时完全重绘 DOM(组件内的 HTML)。 在这种情况下,我假设每次都会重置包装器。

我不确定如何帮助解决这个问题,主要是因为 React 在应用程序中的整个角色实际上只是管理 DOM 的状态,而该脚本正在尝试编辑 DOM,但没有告诉 React。 React可能检测到对 DOM 的无效更改,然后试图纠正它,但我真的不认为 React 会这样做。无论如何,问题是 React 试图管理 DOM,而另一件事是试图编辑 DOM,这不会有好结果。

如果你有一个异步调用其他服务并接收数据的脚本,然后让 React 将该数据应用于 DOM,而不是让脚本编辑 DOM 本身,那就更好了。 当然,您可能无法控制外部脚本的实际工作方式,这就是为什么我说我不知道如何提供帮助。

最新更新