我正在尝试从firebase加载一些图像,并使用火车头滚动反应模块水平滚动它们。但是,每当我添加下面的useEffect部分来初始化火车头卷轴时,我都会得到以下错误:

我已经遵循了LocomotiveScroll的网站和GitHub页面上的所有说明,还查看了其他示例,但似乎无法理解。或者甚至可能我错过了什么。
import React, { useEffect } from "react";
import useFirestore from "../../Hooks/useFirestore";
import "./Astro.css";
import LocomotiveScroll from "locomotive-scroll";
//<a class="gallery__item-link">explore</a>
const Astro = (props) => {
const { docs } = useFirestore("astro");
let i = 1;
const scrollReff = React.createRef();
useEffect(() => {
const scroll = new LocomotiveScroll({
el: scrollReff.current,
smooth: true,
direction: "horizontal"
});
});
return (
<div>
{docs &&
docs.map((doc) => (
<div key={doc.id}>
<div ref={scrollReff}>
<div className="content">
<div className="gallery">
<figure className="gallery__item">
<div className="gallery__item-img">
<div class="gallery__item-img">
<div
class="gallery__item-imginner"
>
<img src={doc.url} alt={doc.description} />
</div>
</div>
</div>
<figcaption className="gallery__item-caption">
<h2
className="gallery__item-title"
data-scroll
data-scroll-speed="1"
>
{doc.title}
</h2>
<span className="gallery__item-number">{"0" + i++}</span>
</figcaption>
</figure>
</div>
</div>
</div>
</div>
))}
</div>
);
};
export default Astro;发布于 2021-05-12 11:57:26
React.createRef()是异步的,所以如果您试图在useEffect中访问它,它将返回null。这意味着当你在useEffect内部调用scrollRef.current的时候,你还没有给它分配任何实际的实例。
发布于 2021-08-10 04:30:48
在我看来,您需要添加一个条件,因为这个问题与异步有关。在useEffect中,当这个变量不存在时,您正在使用scrollReff。为什么?因为在渲染中,如果文档存在,则需要进行条件处理。如果您了解useEffect的工作原理,您就会了解第一个渲染useEffect找不到此变量。
const Astro = (props) => {
...
useEffect(() => {
if(!docs) return;
const scroll = new LocomotiveScroll({
...
});
});https://stackoverflow.com/questions/67496862
复制相似问题