1

我正在尝试从 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;
4

2 回答 2

0

从我的角度来看,您需要添加一个条件,因为此问题与异步有关。在 useEffect 中,当此变量不存在时,您正在使用 scrollReff。为什么?因为在渲染中,如果存在文档,您正在调节。如果你了解 useEffect 是如何工作的,你就会明白第一次渲染 useEffect 是找不到这个变量的。

const Astro = (props) => {
  ...

  useEffect(() => {
    if(!docs) return;
    const scroll = new LocomotiveScroll({
      ...
    });
  });
于 2021-08-10T04:30:48.067 回答
0

React.createRef() 是异步的,因此如果您尝试在 中访问它useEffect,它将返回null。这意味着在你调用scrollRef.currentinside的那一刻useEffect,你还没有为它分配任何真实的实例。

于 2021-05-12T03:57:25.623 回答