【问题标题】:change date using useState reactjs使用 useState reactjs 更改日期
【发布时间】:2021-09-20 10:54:37
【问题描述】:

app.js 文件

import React, { useState } from 'react';
import Header from '../header/header';
import Day from '../day/day'
import {BrowserRouter as Router} from 'react-router-dom';
import './app.css';

export default function App() {
        const [currentDay, setDay] = useState(new Date());
        console.log(currentDay)
        function nextDay() {
            console.log("next clicked");
            let nextDate = new Date(currentDay.getTime());
            nextDate = nextDate.setDate(nextDate.getDate() + 1);
            setDay(nextDate);

        }
        return (
            <>
            <Router>
                <Header/>
            </Router>
            <Day 
            date={currentDay}
            nextDay={nextDay}/>
            </>
        )
}

day.js 文件包含 Day - 组件

import React from 'react';
import Moment from 'react-moment';
import './day.css';

export default function Day({date, nextDay}) {
    return (
        <div className="day-container">
            <Moment>{date}</Moment>
            <span onClick={() => nextDay()}>next</span>
        </div>
    )
}

点击下一步后,日期对象变为时间戳,第二次点击后抛出错误(currentDay.getTime 不是函数)我不明白这是为什么。

【问题讨论】:

    标签: reactjs use-state


    【解决方案1】:

    Date.prototype.setDate 更新日期并返回日期的纪元值。

    您不需要返回值,只需这样做:

    let nextDate = new Date(currentDay.getTime());
    nextDate.setDate(nextDate.getDate() + 1);
    setDay(nextDate);
    

    您的原始变量仍然可以使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-16
      • 2022-12-23
      • 2019-03-13
      • 2021-09-30
      • 1970-01-01
      • 1970-01-01
      • 2020-12-22
      • 2010-10-23
      相关资源
      最近更新 更多