簡體   English   中英

反應。 getTime() 函數不更新狀態

[英]React. getTime() function does not update the state

我試圖通過外部函數getTime()更新組件Demoss的狀態。 我想在頁面加載state time開始更新state time中的state time 為了使它成為現實,我在componentDidMount調用了它。 但由於某些原因,它不會發生。

import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import './index.css';

function getTime() {
  let a = setInterval(() =>
    {new Date()}, 1000 
  );
  return a;
}

class Demoss extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      time: '',
      timer: false
    };

    this.handleClick = this.handleClick.bind(this);
  }

  componentDidMount() {
    this.setState({
      time: getTime() // invoke setInterval state update, but it does not work
    });
  }

  componentWillUnmount() {
    clearInterval(getTime());
  }

  handleClick() {
    this.setState(prevState => ({
        timer: !prevState.timer
    }));

    if (this.state.timer === false) {
      clearInterval(this.timerId);
    } else if (this.state.timer === true) {
    }
  }

  render() {
    return (
      <div>
        <p>{this.state.time.toString()}</p>
        <button onClick={this.handleClick}><Dimes timer={this.state.timer}/></button>
      </div>
    );
  }
}

class Dimes extends React.Component {
  render() {
    if (this.props.timer === true) {
      return (
        <React.Fragment>
          Start timer again!
        </React.Fragment>
      );
    } else {
      return (
        <React.Fragment>
          Start timer!
        </React.Fragment>
      );      
    }

  }
}

ReactDOM.render(
<Demoss />,
document.getElementById('root'));

通過進行以下更改,它將更新時間並重新渲染組件。

 let timeTicker = (self)=>  {self.setState({
    time:new Date().toString()
});}

class Demoss extends React.Component {

  componentDidMount(){
    let timer=setInterval(()=>timeTicker(this),1000);  
    this.setState({timer:timer});

 // keep the setInterval reference in state just so you can call clearInterval on this on `componentWillUnmount` hook
  }


  componentWillUnmount(){
    clearInterval(this.state.timer);
  }

}

new Date().toString()只是為了測試我將日期轉換為字符串,但我認為在渲染之前您必須將其格式化為字符串。

我確實省略了handleClick func 你可以弄清楚

你的代碼有一些錯誤,所以我重寫了它。

import React from "react";
import ReactDOM from "react-dom";
import PropTypes from "prop-types";

class Demoss extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      start_time: new Date(),
      now_time: new Date(),
      timer: false
    };

    this.handleClick = this.handleClick.bind(this);
    this.timer = this.timer.bind(this);
  }

  componentDidMount() {
    setInterval(this.timer, 1000);
  }

  componentWillUnmount() {
    // use intervalId from the state to clear the interval
    clearInterval(this.state.intervalId);
  }

  handleClick() {
    const state = this.state;

    state.start_time = new Date();
    state.now_time = new Date();
    if(!this.state.timer)
      state.timer = true;

    this.setState(state);
  }

  timer() {
    if(this.state.timer)
      this.setState({ now_time : new Date()});
  }

  render() {
    const getTimeDiff = (start_time, now_time) => {
      return Math.round((now_time.getTime() - start_time.getTime()) / 1000);
    };

    return (
      <div>
        <p>{getTimeDiff(this.state.start_time, this.state.now_time)}</p>
        <Dimes handleClick={this.handleClick} timer={this.state.timer} />
      </div>
    );
  }
}

class Dimes extends React.Component {
  render() {
    const renderButtonText = timer => {
      let text = "Start timer";
      if (timer) text += " again!";
      else text += "!";
      return text;
    };

    return (
      <button onClick={this.props.handleClick}>
        {renderButtonText(this.props.timer)}
      </button>
    );
  }
}

ReactDOM.render(<Demoss />, document.getElementById("root"));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM