【问题标题】:useRef array element is undefined / null in a weird wayuseRef 数组元素以一种奇怪的方式未定义/为空
【发布时间】:2022-01-18 02:08:25
【问题描述】:

当我按下 Prev 时,useRef 数组不是未定义的:

但是,当我按下 Next 时,useRef 数组为空:

两个按钮在点击时运行相同的功能(至少在 console.log 之前)但给出不同的结果。

我尝试过以不同的顺序运行它们以及想到的所有其他内容。

感谢任何帮助。

import React, { Suspense, useRef, useEffect, useState } from "react";
import { Canvas, useFrame } from "@react-three/fiber";
import { OrbitControls } from "@react-three/drei";

import BlankPageFlip from "./BlankPageFlip";

const App = () => {
  const refs = useRef([]);

  const numPages = 10;

  const pagesArr = [];

  let currentPage = 0;

  const [playing, setPlaying] = useState(false);
  const speed = Math.PI / 1000;

  const playAnim = (dir) => {
    console.log(refs.current); <------ THIS CONSOLE LOG

    if (refs.current[currentPage]) {
      setPlaying(dir);

      if (dir) currentPage++;
      else currentPage--;

      if (currentPage < 0) currentPage = 0;
      if (currentPage === numPages) currentPage = numPages - 1;
    }
  };

  useEffect(() => {
    for (let i = 0; i < numPages; i++) {
      pagesArr.push(
        <BlankPageFlip
          key={i}
          ref={(el) => (refs.current[i] = el)}
          position={[-1, 0.02 * i, 0]}
        />
      );
    }
  });

  const Pages = () => {
    useFrame(() => {
      if (playing) {
        if (refs.current[currentPage]) {
          if (refs.current[currentPage].rotation.z < Math.PI - 0.03) {
            refs.current[currentPage].rotation.z += speed;
          }
        }
      } else {
        if (refs.current[currentPage]) {
          if (refs.current[currentPage].rotation.z > 0) {
            refs.current[currentPage].rotation.z -= speed;
          }
        }
      }
    });

    return pagesArr;
  };

  return (
    <>
      <div className="NavButtons">
        <button className="prev" onClick={() => playAnim(false)}>
          Prev
        </button>
        <button className="next" onClick={() => playAnim(true)}>
          Next
        </button>
      </div>
      <Canvas
        className="canvas"
        colorManagement
        camera={{ position: [0, 3.7, 0], fov: 60, far: 50 }}
      >
        <ambientLight intensity={2.0} />
        <Suspense fallback={null}>
          <Pages />
          <OrbitControls />
        </Suspense>
      </Canvas>
    </>
  );
};

export default App;

【问题讨论】:

    标签: javascript reactjs react-three-fiber


    【解决方案1】:

    显然,useState 不是您在执行此操作时应该使用的东西。我删除了 useState,现在我只是将它用作 let bool。它现在按预期工作。

    【讨论】:

      猜你喜欢
      • 2012-02-05
      • 1970-01-01
      • 1970-01-01
      • 2017-01-17
      • 2017-12-04
      • 1970-01-01
      • 1970-01-01
      • 2019-08-03
      • 2013-09-29
      相关资源
      最近更新 更多