【问题标题】:Gatsby not loading useEffect function in productionGatsby 没有在生产环境中加载 useEffect 函数
【发布时间】:2020-03-09 13:42:34
【问题描述】:

我正在使用 Gatsby.js 创建一个网站。 在我的组件中,我在 useEffect 函数中使用 Gsap 创建了动画。

调试时,一切正常。在生产中useEffect函数没有运行,没有显示动画。

我该怎么办? 有什么想法吗?

感谢您的回答!

我的组件:

import React, { useRef, useEffect } from "react"
import styled from "styled-components"
import gsap from "gsap"
import WhatEver from "../../../static/whatever.svg"
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faArrowDown } from '@fortawesome/free-solid-svg-icons'
import scrollTo from 'gatsby-plugin-smoothscroll';


const HeaderWrapper = styled.header`
  width: 100%;
  height: 100vh;
  min-height: 150px;
  padding: 10px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;

  background-color: rgb(255, 216, 41);
`

const HeaderButton = styled.button`
  display: block;
  margin: 40px auto;
  border: 2px solid #000000;
`

const HeaderComponent = () => {

  const animWrapper = useRef(null)

  useEffect(() => {

    const [elements] = animWrapper.current.children

    const what = elements.getElementById('What')
    const ever = elements.getElementById('Ever')
    const button = document.getElementById('header-button')
    const icon = document.getElementById('header-icon')

    const whatChildrens = what.children
    const everChildrens = ever.children
    const allChildrens = [...whatChildrens, ...everChildrens]

    gsap.set([...allChildrens, button], { autoAlpha: 0 })

    const timeLine = gsap.timeline({ defaults: { ease: 'power3.inOut' } })

    timeLine
      .to(whatChildrens, { autoAlpha: 1, duration: 0.75 })
      .to(everChildrens, { autoAlpha: 1, stagger: 0.025 })
      .to(button, { autoAlpha: 1 })
  }, [])

  return (
      <HeaderWrapper className="header" id="main-header">
        <div ref={animWrapper} id="header-logo-wrapper">
          <WhatEver style={{width: '100%'}}/>

          <HeaderButton id="header-button" onClick={() => scrollTo('#poznaj-nas')}>
            <FontAwesomeIcon icon={faArrowDown} id="header-icon"/>
          </HeaderButton>
        </div>
      </HeaderWrapper>
  )
}

export default HeaderComponent

【问题讨论】:

  • @TomOakley 准备好了!
  • 你怎么知道useEffect 钩子没有运行?您是否添加了console.log 或使用调试器来建立它?是否有可能它正在运行但函数内的内容在生产中不起作用?
  • 是的,我添加了console.log。开发期间的控制台日志,但不在生产中。
  • 所以我们现在可以忽略 gsap,因为它只会增加混乱吗?核心问题是useEffect 不能在生产环境中工作,对吧?
  • 嗯,这太奇怪了。您是否尝试过从返回的 JSX 中删除内容?你能在 codepen.io(或类似网站)上重现吗?

标签: javascript reactjs gatsby gsap


【解决方案1】:

我认为正在发生的事情是 gsap 库正在从生产构建中摆脱出来。我会尝试调整你的 webpack 设置以确保它没有被删除,或者像这样包含它:

const gsap = require("gsap")

根据我的经验,这会阻止库被树淘汰。

【讨论】:

    猜你喜欢
    • 2019-04-14
    • 2021-11-10
    • 2019-08-06
    • 1970-01-01
    • 2020-04-20
    • 1970-01-01
    • 1970-01-01
    • 2021-11-08
    • 2023-03-10
    相关资源
    最近更新 更多