javascript 未捕获引用错误:在初始化之前无法访问"allNewDice ...". reactjs useState

lstz6jyr  于 2022-12-21  发布在  Java
关注(0)|答案(2)|浏览(180)

嗨朋友们::::需要帮助:::我试图写代码,但我得到了一个消息:::::::未捕获引用错误:无法在初始化之前访问"allNewDice"....任何人都可以帮助我解决这个问题....请

import "./Main.css";
import Dices from "../Dices/Dices";
import React from "react";
const Main = () => {
  const [dice, setDice] = React.useState(allNewDice());

  const allNewDice = () => {
    const newDice = [];
    for (let index = 0; index < 10; index++) {
      const randomNumber = Math.ceil(Math.random() * 6);
      newDice.push(randomNumber);
    }
    return newDice;
  };

  const rollDice = () => {
     setDice(allNewDice());
  }
  const diceElement = dice.map((die) => {
    <Dices value={die} />;
  });

  return (
    <main>
      <div className="dice-container">{diceElement}</div>
      <button onClick={rollDice}>Roll</button>
    </main>
  );
};

export default Main;

.....................

import "./Dices.css";

const Dices = (props) => {
  return <div className="dice"> {props.value} </div>;
};

export default Dices;
sr4lhrrt

sr4lhrrt1#

该错误告诉您:在初始化之前无法访问“allNewDice”。您需要在调用allNewDice函数之前对其进行初始化和声明。

// * Initializing allNewDice
const allNewDice = () => {
  const newDice = [];
  for (let index = 0; index < 10; index++) {
    const randomNumber = Math.ceil(Math.random() * 6);
    newDice.push(randomNumber);
  }
  return newDice;
};  

// * Calling allNewDice()
const [dice, setDice] = React.useState(allNewDice());
lpwwtiir

lpwwtiir2#

allNewDice函数是在骰子状态的初始值中调用之后定义的。
若要修复此错误,可以在作为状态初始值传递的表达式内调用函数:

const [dice, setDice] = React.useState((() => allNewDice())());

希望这个有用。

相关问题