1

根据 GatsbyJS 的创建者,这似乎是一个常见问题。这是 GitHub repo 上已解决问题的引用:

您有引用窗口对象的代码(您自己的或正在使用的模块)。服务器渲染时失败,因为您不在浏览器中,因此窗口不存在。这是一个相当普遍的问题。解决方案是在 componentDidMount 中运行对窗口的代码引用,您可以确保您现在在浏览器中。

我只看到少数几个在 ReactJS 中设置 AOS 或在 GatsbyJS 中设置类似东西的示例,但没有什么是我真正需要的。我提出的配置不适用于生产版本,即“gatsby build”......这是我的代码:

import React from 'react'
import {Link} from 'react-router'
import {prefixLink} from 'gatsby-helpers'
import {config} from 'config'
import AOS from 'aos'

import '../static/css/reset.css'
import '../static/css/typography.css'
import '../static/css/base.css'
import '../static/css/w3.css'
import '../static/css/aos.css'
import '../static/css/devicons.css'

class Template extends React.Component {

componentDidMount() {
  AOS.init()
}

render() {
    const {location, children} = this.props

    return (
        <div>
            <div className='wrapper'>
                {children}
            </div>
        </div>
    );
}

}

Template.propTypes = {
    children: React.PropTypes.any,
    location: React.PropTypes.object,
    route: React.PropTypes.object
}

export default Template

我尝试了一些变体,我在 props 构造函数中将变量设置为 AOS,然后使用 componentDidMount 将变量设置为 AOS.init(),还尝试使用 this.state 并进行设置,但都没有任何区别。那么执行所需操作的正确方法是什么?我知道我将使用 componentDidMount 但除此之外我不知道。任何帮助深表感谢...

4

2 回答 2

4

我终于意识到我已经忘记了另一个启动 Gatsby 项目是如何处理 Wow.js 的......这就是解决我的问题的原因,基于他们在 Gatstrap, Gatsby 启动博客中的示例:

componentDidMount() {
    const AOS = require('aos');
    this.aos = AOS
    this.aos.init()
}

componentDidUpdate() {
    this.aos.refresh()
}

希望这对其他人有帮助!

于 2017-03-03T02:38:03.197 回答
2

我使用 React Hooks (16.8+) 解决了它

let AOS;
  useEffect(() => {
    /**
     * Server-side rendering does not provide the 'document' object
     * therefore this import is required either in useEffect or componentDidMount as they
     * are exclusively executed on a client
     */
    const AOS = require("aos");
    AOS.init({
      once: true,
    });
  }, []);

  useEffect(() => {
    if (AOS) {
      AOS.refresh();
    }
  });
于 2019-12-29T20:30:19.827 回答