如何在 React 中的特定函数上添加延迟?

我构建了一个石头/剪刀/布 React 应用程序。该应用程序工作正常,我只是想在 CPU 必须选择武器(石头/布/剪刀)时添加一些延迟。

我希望有一个时间窗口,CPU 选择的图像不会出现在屏幕上,而用户的选择会立即出现在屏幕上。

我尝试在 compounentDidMount() 方法中添加 setInterval() 函数,但没有成功。

如何仅在 CPU 部分添加延迟?

https://codesandbox.io/s/nice-ardinghelli-96sum?file=/src/components/Main.js

预先非常感谢您。


喵喔喔
浏览 205回答 4
4回答

慕丝7291255

您需要添加一个不渲染任何内容的状态。例如,只需将 cpu 选择设置为 4 并更新渲染函数。然后你可以像这里一样添加睡眠功能。我做了一些我认为你想要的工作示例我对你的代码所做的主要更改是this.sleep(1500).then(() => {      const index = getRandomInt(3);      this.setState({        houseChoice: index      });      const results = this.getResults(choiceName, index).toUpperCase();      this.setState({        results: results      });      /*****************calling setScore()********************/      if (results === "WIN") {        this.props.setScore(1);      } else if (results === "LOSE") {        this.props.setScore(-1);      } else {        this.props.setScore(0);      }    });其中handleClick执行超时。在结果页面中我添加了this.state.houseChoice === 2 ? (             /*3*/              <div                className="elem-container result-container"                style={{                  borderColor: "hsl(349, 71%, 52%)",                  color: "hsl(349, 70%, 56%)"                }}              >                <img src={rock} className="choice-image" alt="img" />              </div>            ) : null

开满天机

人类玩家选择一步棋后,不要立即让 CPU 选择一步棋。实现componentDidUpdate生命周期函数并将CPU的选择逻辑移到那里。这也需要移动对获胜逻辑的检查。/*function that handles the user choice*/handleClick = (&nbsp; choiceName,&nbsp; choiceImage,&nbsp; choiceBorderColor,&nbsp; choiceExtraBorderColor) => () => {&nbsp; this.setState({&nbsp; &nbsp; onScreen: false,&nbsp; &nbsp; choiceName,&nbsp; &nbsp; choiceImage,&nbsp; &nbsp; choiceBorderColor,&nbsp; &nbsp; choiceExtraBorderColor&nbsp; });};一旦人类玩家选择了一个动作,就获得房子的随机动作,但不要立即将状态更新排入队列,而是稍后使用进入setTimeout更新状态。仅当两个玩家都选择了移动但结果尚未计算并存储在状态中时才检查胜利。componentDidUpdate(prevProps, prevState) {&nbsp; if (&nbsp; &nbsp; prevState.choiceName !== this.state.choiceName &&&nbsp; &nbsp; this.state.choiceName&nbsp; ) {&nbsp; &nbsp; function getRandomInt(max) {&nbsp; &nbsp; &nbsp; return Math.floor(Math.random() * Math.floor(max));&nbsp; &nbsp; }&nbsp; &nbsp; const index = getRandomInt(3);&nbsp; &nbsp; setTimeout(() => {&nbsp; &nbsp; &nbsp; this.setState({&nbsp; &nbsp; &nbsp; &nbsp; houseChoice: index&nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }, 2000);&nbsp; }&nbsp; if (&nbsp; &nbsp; this.state.choiceName &&&nbsp; &nbsp; [0, 1, 2].includes(this.state.houseChoice) && // We want 0 to be truthy :)&nbsp; &nbsp; !this.state.results&nbsp; ) {&nbsp; &nbsp; const results = this.getResults(&nbsp; &nbsp; &nbsp; this.state.choiceName,&nbsp; &nbsp; &nbsp; this.state.houseChoice&nbsp; &nbsp; ).toUpperCase();&nbsp; &nbsp; this.setState({&nbsp; &nbsp; &nbsp; results: results&nbsp; &nbsp; });&nbsp; &nbsp; /*****************calling setScore()********************/&nbsp; &nbsp; if (results === "WIN") {&nbsp; &nbsp; &nbsp; this.props.setScore(1);&nbsp; &nbsp; } else if (results === "LOSE") {&nbsp; &nbsp; &nbsp; this.props.setScore(-1);&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; this.props.setScore(0);&nbsp; &nbsp; }&nbsp; }}有条件地渲染“等待 CPU”UI<h4 className="result-title">&nbsp; {this.state.houseChoice === ""&nbsp; &nbsp; ? "THE HOUSE CHOOSING"&nbsp; &nbsp; : "THE HOUSE PICKED"}</h4>{this.state.houseChoice === "" ? (&nbsp; <div>...</div>) : this.state.houseChoice === 0 ? (&nbsp; /*1*/&nbsp; <div&nbsp; &nbsp; className="elem-container result-container"&nbsp; &nbsp; style={{&nbsp; &nbsp; &nbsp; borderColor: "hsl(230, 89%, 62%)",&nbsp; &nbsp; &nbsp; color: "hsl(230, 89%, 65%)"&nbsp; &nbsp; }}&nbsp; >&nbsp; &nbsp; <img src={paper} className="choice-image" alt="img" />&nbsp; </div>) : this.state.houseChoice === 1 ? (&nbsp; /*2*/&nbsp; <div&nbsp; &nbsp; className="elem-container result-container"&nbsp; &nbsp; style={{&nbsp; &nbsp; &nbsp; borderColor: "hsl(39, 89%, 49%)",&nbsp; &nbsp; &nbsp; color: "hsl(40, 84%, 53%)"&nbsp; &nbsp; }}&nbsp; >&nbsp; &nbsp; <img src={scissors} className="choice-image" alt="img" />&nbsp; </div>) : (&nbsp; /*3*/&nbsp; <div&nbsp; &nbsp; className="elem-container result-container"&nbsp; &nbsp; style={{&nbsp; &nbsp; &nbsp; borderColor: "hsl(349, 71%, 52%)",&nbsp; &nbsp; &nbsp; color: "hsl(349, 70%, 56%)"&nbsp; &nbsp; }}&nbsp; >&nbsp; &nbsp; <img src={rock} className="choice-image" alt="img" />&nbsp; </div>)}有条件地渲染结果并重试按钮。<div className="final-result-container">&nbsp; {this.state.results && (&nbsp; &nbsp; <>&nbsp; &nbsp; &nbsp; <h1 className="bold">YOU {this.state.results}</h1>&nbsp; &nbsp; &nbsp; <TryAgain onClick={this.handleTryAgainClick} />&nbsp; &nbsp; </>&nbsp; )}</div>再次玩时不要忘记重置所有状态handleTryAgainClick() {&nbsp; this.setState({&nbsp; &nbsp; onScreen: true,&nbsp; &nbsp; choiceName: "",&nbsp; &nbsp; choiceImage: "",&nbsp; &nbsp; choiceBorderColor: "",&nbsp; &nbsp; choiceExtraBorderColor: "",&nbsp; &nbsp; houseChoice: "",&nbsp; &nbsp; results: ""&nbsp; });}

噜噜哒

我不确定我的问题是否正确,但这里是,如果要在渲染上设置延迟,那么在做出选择之前不要渲染。如果应用程序必须在玩家输入后执行某些操作,请使用 async wait 异步执行以下操作。

忽然笑

如果我猜对了,也许 lodash 的 Debounce 会为你提供答案。我在我的井字游戏应用程序中使用它来延迟计算机移动。只需从 NPM 添加即可npm&nbsp;install&nbsp;lodash&nbsp;—save-dev然后导入到你的文件中import&nbsp;{debounce}&nbsp;from&nbsp;'lodash';不断创建将去抖的内容,您从 lodash 中调用了它。500 是时间,您想要移动延迟多少时间。在这种情况下,它将是 0.5 秒。const&nbsp;debounceComputerMove&nbsp;=&nbsp;debounce(()=>{ &nbsp;&nbsp;computerMove(); },500);然后当你想调用computerMove函数时,调用debounceComputerMove而不是computerMove()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript