在React状态组件中调用setInterval方法时,日期对象未更新

时间:2019-12-04 17:04:38

标签: javascript reactjs components setinterval stateful

我是新来的反应者,我正在尝试练习有状态的组件。我的目标是使用setInterval方法更新小时,分钟和秒。我首先尝试使用 this.setState({ seconds: date.getSeconds() }) 但无济于事。然后,我尝试使用prevState方法。有人知道我在想什么吗?

这是我的完整代码:


import InputDisplay from './components/InputDisplay';

class Stateful extends Component {
    constructor(props){
        super(props);

        this.state = {
            inputName: "",
            inputValue: "Juice",
            hour: 0,
            minute: 0,
            seconds: 0
        }
    }

    componentDidMount() {
        this.startClock();
    }

    handleOnChangeInput = (e) => {
        let {name, value} = e.target

        this.setState({
            [name]: name,
            inputValue: value
        })
    }

    startClock = () =>{
        const date = new Date();

        setInterval(() =>{
            console.log(this.state.seconds);
            let seconds = date.getSeconds()
            console.log(seconds);
            this.setState(prevState => {
                return {
                    hour: prevState.hour = date.getHours(),
                    minute: prevState.minute = date.getMinutes(),
                    seconds: prevState.seconds = date.getSeconds()
                }
            })
        }, 1000
        )
    }


    render(){
        return(
            <div>
                <h1>Hello this is Stateful Input: {this.state.inputValue} </h1>
                <InputDisplay 
                    name={this.state.inputName}
                    value= {this.state.inputValue}
                    onChange= {this.handleOnChangeInput}
                />

                <h3>H:{this.state.hour} M:{this.state.minute} S:{this.state.seconds}</h3>
            </div>
        )
    }
}

export default Stateful;```

1 个答案:

答案 0 :(得分:0)

我发现您的代码存在一些问题。

1)设置状态不正确

2)您需要在状态中存储intervalId并清除组件卸下时的时间间隔

像这样尝试:

import InputDisplay from './components/InputDisplay';

class Stateful extends Component {
    constructor(props){
      super(props);

      this.state = {
        inputName: "",
        inputValue: "Juice",
        hour: 0,
        minute: 0,
        seconds: 0,
        intervalId: null,
      }
    }

    componentDidMount() {
      const intervalId = setInterval(this.startClock, 1000);
      // store intervalId in the state so it can be accessed later:
      this.setState({intervalId: intervalId});
    }

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

    startClock = () => {
      const date = new Date();
      const hour = date.getHours()
      const minute = date.getMinutes()
      const seconds = date.getSeconds()

      this.setState({
        hour,
        minute,
        seconds
      })
    }

    handleOnChangeInput = (e) => {
      let {name, value} = e.target

      this.setState({
        [name]: name,
        inputValue: value
      })
    }

    render(){
        return(
            <div>
                <h1>Hello this is Stateful Input: {this.state.inputValue} </h1>
                <InputDisplay 
                    name={this.state.inputName}
                    value= {this.state.inputValue}
                    onChange= {this.handleOnChangeInput}
                />

                <h3>H:{this.state.hour} M:{this.state.minute} S:{this.state.seconds}</h3>
            </div>
        )
    }
}

export default Stateful;