【问题标题】:React - Uncaught ReferenceError: combinations is not definedReact - 未捕获的 ReferenceError:未定义组合
【发布时间】:2023-01-12 05:48:09
【问题描述】:

我正在为使用 React 的网站构建一个小工具。但是当它说我的变量“组合”未定义以及存在 TypeError: wrapper is null 时,它给了我一个参考错误。它有效,但同时它给出了一个恒定的错误。

import React from 'react';
import './portfolio.css';

const wrapper = document.getElementById("wrapper");
console.log(wrapper)
const rand = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);

const uniqueRand = (min, max, prev) => {
  let next = prev;
  while(prev === next) next = rand(min, max);
  
  return next;
}

const combinations = [
  { configuration: 1, roundness: 1 },
  { configuration: 1, roundness: 2 },
  { configuration: 1, roundness: 3 },
  { configuration: 2, roundness: 2 },
  { configuration: 2, roundness: 3 }
];

let prev = 0;

setInterval(() => {
  const index = uniqueRand(0, combinations.length - 1, prev),
        combination = combinations[index];
  
  wrapper.dataset.configuration = combination.configuration;
  wrapper.dataset.roundness = combination.roundness;
  
  prev = index;
}, 3000);

const Portfolio = () => {
  return (
    <div className='RO__portfolio'>
      <div className='RO__portfolio-content' data-roundness="1" data-configuration ="1" id='wrapper'>
        <div className='RO__portfolio-content_shape'></div>
        <div className='RO__portfolio-content_shape'></div>
        <div className='RO__portfolio-content_shape'></div>
        <div className='RO__portfolio-content_shape'></div>
        <div className='RO__portfolio-content_shape'></div>
        <div className='RO__portfolio-content_shape'></div>
        <div className='RO__portfolio-content_shape'></div>
      </div>
    </div>
  )
}

export default Portfolio

它不应该给这个错误:

  • 未捕获的 ReferenceError:未定义组合

  • 未捕获的类型错误:包装器为空

【问题讨论】:

  • 要在 React 中访问 dom 元素,你应该使用 refs

标签: javascript node.js reactjs json


【解决方案1】:

document.getElementById("wrapper") 在文件导入后立即触发,而不是在页面加载后触发。这应该可以在 Portfolio 函数中设置 - 与 setInterval 回调一样。

编辑:也同意关于 refs 的评论

【讨论】:

    猜你喜欢
    • 2016-05-22
    • 2016-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-13
    • 1970-01-01
    相关资源
    最近更新 更多