[英]How to call loading function with React useEffect only once
[英]Gatsby not loading useEffect function in production
我正在使用 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
我認為正在發生的事情是 gsap 庫正在從生產構建中擺脫出來。 我會嘗試調整你的 webpack 設置以確保它沒有被刪除,或者像這樣包含它:
const gsap = require("gsap")
以我的經驗,這阻止了圖書館被樹搖晃。
我遇到了這個問題,只需按照以下步驟解決:
如果您嘗試在沒有任何 Web 服務器的情況下直接打開 html,則不會調用 useEffect。
解決此問題的唯一方法是運行網絡服務器並從服務器提供 html。
我使用的是 mac 系統,所以使用公共文件夾中的命令運行 python 服務器:
python -m SimpleHTTPServer 8000
然后使用 localhost:8000 打開它
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.