首页 > 解决方案 > 在 React 有状态组件中调用 setInterval 方法时日期对象未更新

问题描述

我是新手,我正在尝试练习有状态的组件。我的目标是使用 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;```

标签: javascriptreactjscomponentssetintervalstateful

解决方案


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

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;

推荐阅读