React - timed操作不会加载特定组件

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了React - timed操作不会加载特定组件相关的知识,希望对你有一定的参考价值。

我想要的是:当计时器达到0秒时,应用程序会安装一个组件并隐藏其他组件。会发生什么:没有。

我正在研究React单页面应用程序。当它达到0时我对计时器的行为有问题。我希望它隐藏问题和计时器组件并仅显示结果组件。现在,逻辑是在timerZero中,但我确实尝试将它放在startTimer和/或clickStart中,但这些组合都不起作用。

我还注意到,如果你在计时器命中0后选择答案,它将继续控制台记录“时间到了!”在每个选择。在0秒后点击提交仍然会带您到resultsDiv并获得正确的分数,但不会按照指示隐藏计时器。

回购:赌场

应用

https://github.com/irene-rojas/pixar-react

小时

import React, { Component } from 'react';
import './App.css';
import Timer from "./Timer";
import Questions from "./Questions/Questions.js";
import Results from "../src/Results";

class App extends Component {

state = {
    totalTrue: 0,
    totalFalse: 0,
    showTimer: true,
    showQuestions: false,
    showResults: false,
}

clickStart = (event) => {
    event.preventDefault();
    console.log("start button clicked");
    this.setState(
        {showQuestions: true}
    )
}

// submit button
handleFormSubmit = (event) => {
    event.preventDefault();
    console.log("submit button clicked");
    this.setState(
        {showResults: true,
        showQuestions: false,
        showTimer: false}
        // timer still appears in resultsDiv
    )
};

timerZero = () => {
    if (this.state.timer === 0) {
    this.setState(
        {showResults: true,
        showQuestions: false,
        showTimer: false}
    )
    }
    // nothing happens >:(
};

callbackHandlerFunction = ( selectedOption ) => {
    const answerValue = selectedOption.value;
    if (answerValue === true) {
        this.setState({totalTrue: this.state.totalTrue + 1}, () => {
            console.log(`New TotalTrue: ${this.state.totalTrue}`);
        });
    };
    if (answerValue === false) {
        this.setState({totalFalse: this.state.totalFalse + 1}, () => {
            console.log(`New TotalFalse: ${this.state.totalFalse}`);
        });
    };
  } 

  render() {
    return (

  <div className="parallax">

    <div className="App">

        <div className="wrapper">

        <div className="headerDiv">
            <h1>Pixar Trivia!</h1>
        </div>

        <div className="timerDiv">
            <Timer 
            handleTimerClick={this.clickStart}
            timeOut={this.timerZero}
            />   
        </div>

        {this.state.showQuestions &&
        <div className="questionSection">
            <Questions 
                handleClickInParent={this.callbackHandlerFunction}
            />

            <div>
                <button onClick={this.handleFormSubmit}>Submit</button>
            </div>
        </div>
        }

        {this.state.showResults && 
        <div className="resultsDiv">
            <Results 
                totalTrue={this.state.totalTrue}
                totalFalse={this.state.totalFalse}
            />
        </div>
        }

        </div>

    </div>

  </div>
    );
  }
}

export default App;
答案

我发现你的代码出了什么问题,我只是想在错误的地方分手。

App.js

import React, { Component } from 'react';

class Timer extends Component {

  state = {
    timer: 10
  };

  startTimer = (event) => {
    this.timer = setInterval(() => this.setState({
      timer: this.state.timer - 1}), 1000); 
    // onClick, load Questions
    this.props.handleTimerClick(event);
   };

  stopTimer = () => {
    clearInterval(this.timer);
    console.log("Time's up!");
    this.props.timeOut();
  };

  render() {
    return (
      <div className="Timer">
        <div>{this.state.timer} seconds</div>
        <button onClick={this.startTimer}>Start!</button>
        {this.state.timer === 0 && this.stopTimer()}
      </div>
    );
  }
}

export default Timer;

Timer.js

// ...
/* 
    you were trying to read this.state.timer
    which is not decalred in this component
*/
timerZero = () => this.setState(
        {showResults: true,
        showQuestions: false,
        showTimer: false}
    )

// ...

render() {

{/* ... */}
{this.state.showTimer && (
    <div className="timerDiv">
        <Timer 
        handleTimerClick={this.clickStart}
        timeOut={this.timerZero}
        />  
    </div>
{/* ... */
)} 

另外,我建议您忽略// ... /* I added `shouldComponentUpdate` lifecycle with this, we stop the `Timer` component for rendering and call `stopTimer` (instead of doing it inside the render method) */ shouldComponentUpdate() { console.log(this.state.timer); if (this.state.timer <= 0) { this.stopTimer(); return false; } return true; }; /* Also added the a componentWillUnmount method for good practice here if the component is unmounted the timer won't be running forever. */ componentWillUnmount() { clearInterval(this.timer); }; render() { return ( <div className="Timer"> <div>{this.state.timer} seconds</div> <button onClick={this.startTimer}>Start!</button> {/* delete the call to `this.stopTimer` */} </div> ); } 文件中的node_modules文件夹,以使您的项目更精简。所有项目依赖项都列在.gitignoreyarn.lock中,所以当我下载你的repo时,我会下载你正在使用的相同依赖项。

干杯!!!

以上是关于React - timed操作不会加载特定组件的主要内容,如果未能解决你的问题,请参考以下文章

React + Redux:reducer 不会重新加载组件

React 不会在路由参数更改或查询更改时重新加载组件数据

如何加载新版本react addon

React 根组件不会加载整个 index.html

如果没有在 URL 更改上重新加载页面,React 不会呈现

在js代码中怎样用react 加载组件