NodeJS useEffect()不重新调用作为属性给出的函数

hfsqlsce  于 2023-01-16  发布在  Node.js
关注(0)|答案(1)|浏览(94)

我有一个函数,我传递给我的重用组件作为一个 prop 。这个函数生成并返回两个随机数和他们的加法结果。一切工作在第一次去,但我不知道如何让它生成新的数字和结果提交。
PS:我收到一个关于useEffect依赖的警告,说

React Hook useEffect has a missing dependency: 'calculation'. Either include it or remove the dependency array. If 'setCalculatedNums' needs the current value of 'calculation', you can also switch to useReducer instead of useState and read 'calculation' in the reducer.

但是,使用calculation作为依赖项也不起作用。
PS:在我决定重用不需要重复的代码片段是一个更好的实践之前,我最初的代码工作得很完美。只是不知道如何用这种方式完成它。
下面是代码:
重用组件MainInput.js:

const correctAnswer = <Typography>Correct!</Typography>;
const wrongAnswer = <Typography>Wrong!</Typography>;
const enterAnswer = <Typography>Enter your answer!</Typography>;

const MainInput = ({operation, calculation}) => {
  const [enteredValue, setEnteredValue] = useState("");
  const [correctValue, setCorrectValue] = useState(false);
  const [calculatedNums, setCalculatedNums] = useState({});
  const [isIncorrect, setIsIncorrect] = useState(false);
  const [generateNewNumbers, setGenerateNewNumbers] = useState(false);
  const [haveToEnterAnswer, setHaveToEnterAnswer] = useState(false);

  useEffect(() => {
    
    setCalculatedNums(calculation);
    setGenerateNewNumbers(false);
    setCorrectValue(false);
    setEnteredValue("");
  }, [generateNewNumbers]);

  const submitHandler = () => {
    console.log(calculation.additionResult)
    if (correctValue) {
      
      setGenerateNewNumbers(true);
    }

    if (+enteredValue === calculation.additionResult) {
      setCorrectValue(true);
    } else if (enteredValue.length === 0) {
      setHaveToEnterAnswer(true);
    } else {
      setIsIncorrect(true);
    }
  };

  const inputValueHandler = (value) => {
    setIsIncorrect(false);
    setHaveToEnterAnswer(false);
    setEnteredValue(value);
  };

  const submitOrTryNewOne = () => {
    return correctValue ? "Try new one" : "Submit";
  };

  return (
    <>
      <Navbar />
      <Card
        sx={{
          marginTop: 2,
          height: 50,
          display: "flex",
          flexDirection: "column",
          alignItems: "center",
        }}
      >
        <Typography></Typography>
      </Card>
      <Container component="main" maxWidth="xs">
        <Box
          sx={{
            marginTop: 8,
            display: "flex",
            flexDirection: "column",
            alignItems: "center",
          }}
        >
          <Typography>Fill in the box to make the equation true.</Typography>
          <Typography fontSize={28}>
            {calculatedNums.number1} {operation} {calculatedNums.number2}{" "}
            =
          </Typography>
          <TextField
            inputProps={{ inputMode: "numeric", pattern: "[0-9]*" }}
            type="number"
            name="sum"
            id="outlined-basic"
            label=""
            variant="outlined"
            onChange={(event) => {
              inputValueHandler(event.target.value);
            }}
            disabled={correctValue}
            value={enteredValue}
          ></TextField>
          {haveToEnterAnswer && enterAnswer}
          {correctValue && correctAnswer}
          {isIncorrect && wrongAnswer}

          <Button
            type="button"
            sx={{ marginTop: 1 }}
            onClick={() => submitHandler()}
            variant="outlined"
          >
            {isIncorrect ? "Try again!" : submitOrTryNewOne()}
          </Button>
        </Box>
      </Container>
    </>
  );
};

export default MainInput;

MainArithmetics.js

export const generateNumbersAndResults = () => {
  const randomNum1 = () => {
    return Math.floor(Math.random() * 50);
  };

  const randomNum2 = () => {
    return Math.floor(Math.random() * 50);
  };

  const number1 = randomNum1() || 0;
  const number2 = randomNum2() || 0;

  const additionResult = number1 + number2 || 0;

 

 

  return {
    additionResult,
    number1,
    number2
  };
};

AdditionMain.js

import React from "react";
import MainInput from "../components/MainInput";
import { generateNumbersAndResults } from "../MainArithmetics";

const AdditionMain = () => {
  const operation = '+'
  const calculation = generateNumbersAndResults()

  return (
    <>
    {console.log(calculation)}
      <MainInput
        operation={operation}
        calculation={calculation}
        
      />
    </>
  );
};

export default AdditionMain;
yqkkidmi

yqkkidmi1#

有很多不需要的代码,但核心问题是calculation不会改变,一旦调用,它将有一组固定的数字,所以当你调用:

setCalculatedNums(calculation);

它只会再次设置“相同”的数字。如果您需要新的数字,您需要执行以下操作:

setCalculatedNums(generateNumbersAndResults());

在注解后编辑

核心问题是你传递的不是函数,而是它的结果。如果你想传递函数,而不是:

const calculation = generateNumbersAndResults();

你会想:

const calculation = generateNumbersAndResults;

然后,稍后您要确保在想要生成新的“计算”时调用此函数

setCalculatedNums(calculation());

相关问题