在学习 React 的过程中,只是为了练习目的构建了一个简单的猜数字游戏
在我的代码中,我有一个名为“Game”的组件,其中包含“const roll = Math.floor(Math.random() * 10 + 1)”,用于滚动 1-10 之间的随机数并通过控制台验证滚动.log,这样我就可以看到控制台上显示的数字。
然后,我在 return 语句中使用 {roll},该语句稍后在我的 App.js 文件中实例化(App.js 未在下面显示)
唯一的事情是,使用 console.log(roll) 时滚动的随机数与我的返回语句“滚动的数字是 {roll}”中在屏幕上呈现的数字不同
这是为什么呢?我在普通 JavaScript 中从未遇到过这个问题,但似乎滚动发生了两次,而不是采用“const roll”中的初始值
谁能解释一下为什么会出现这种情况以及如何解决这个问题?感谢您提供的任何帮助
import React, {useState} from "react";
const Game = () => {
const roll = Math.floor(Math.random() * 10 + 1);
console.log(roll);
const guess = () => {
let inputGuess = document.querySelector('.input');
console.log(inputGuess.value);
}
const [lives, setLives] = useState(5);
return (
<React.Fragment>
<h1 className='header'>Guess the number!</h1>
<p className='roll'>The number rolled is <strong>{roll}</strong></p>
<p className='lives'><strong>{lives}</strong> lives remaining</p>
<p className='message'>Enter a number between 1-10</p>
<input type='text' className='input'></input>
<button className='guess' onClick={guess}>Guess</button>
</React.Fragment>
)
}
export default Game;
最佳答案
在开发模式下,有意做出 React invokes function component bodies (and other lifecycle methods) twice帮助识别副作用:
Strict mode can’t automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally double-invoking the following functions:
- 类组件构造函数、render 和 shouldComponentUpdate 方法
- 类组件静态 getDerivedStateFromProps 方法
- 函数组件体
- 状态更新函数(setState 的第一个参数)
- 传递给 useState、useMemo 或 useReducer 的函数
关于javascript - REACT,有一个滚动数字 1-10 的变量,并在 JSX 中的 return 语句中连接该变量。在屏幕上呈现之前,数字会滚动 2 倍,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70320763/