Javascript函数调用返回相同的值?

Javascript函数调用返回相同的值?,javascript,reactjs,Javascript,Reactjs,我已经编写了一个函数来为我格式化一个日期,我在开始日期和结束日期调用它。预期的行为是使用formatDate函数计算开始日期,然后计算结束日期。但是,在我的控制台中,似乎函数调用正确,但随后值都存储为结束日期 这里是我调用函数和设置变量的地方: const setTimeAndDate = () => { let start = formatDate(startTime) let end = formatDate(endTime) cons

我已经编写了一个函数来为我格式化一个日期,我在开始日期和结束日期调用它。预期的行为是使用formatDate函数计算开始日期,然后计算结束日期。但是,在我的控制台中,似乎函数调用正确,但随后值都存储为结束日期

这里是我调用函数和设置变量的地方:

const setTimeAndDate = () => {
        let start = formatDate(startTime)
        let end = formatDate(endTime)

        console.log('in set time and date, the start is: ', start)
        console.log('in set time and date, the end is: ', end)
    }
下面是格式化日期的函数:

const formatDate = (time) => {
        let hour = parseInt(time.substring(0,2)) // 13:51 -> 13
        let minute = parseInt(time.substring(3))
        let d = props.date.date
        d.setHours(hour)
        d.setMinutes(minute)

        console.log('in format date func, the time is: ', d)

        return d;
    }

控制台首先从formatDate()函数打印正确的值,但当它在setTimeAndDate()中打印开始和结束时,它们都是结束值。我肯定这只是我误解的Javascript,但有人能解释一下这里发生了什么吗

您要修改props.date.date两次,因此当然要显示最新的值两次。 如果要查看这两个值,请执行以下操作:

    let start = formatDate(startTime)
    console.log('in set time and date, the start is: ', start)

    let end = formatDate(endTime)
    console.log('in set time and date, the end is: ', end)
或更改formatDate函数:

const formatDate = (time) => {
    let hour = parseInt(time.substring(0,2)) // 13:51 -> 13
    let minute = parseInt(time.substring(3))
    let d = new Date(props.date.date.getTime());
    d.setHours(hour)
    d.setMinutes(minute)

    console.log('in format date func, the time is: ', d)

    return d;
}
使用
新日期(props.Date.Date.getTime())
可以创建与原始日期相同时间的新日期

const formatDate = (time) => {
        let hour = parseInt(time.substring(0,2)) // 13:51 -> 13
        let minute = parseInt(time.substring(3))
        let d = new Date(props.date.date.getTime());
        d.setHours(hour)
        d.setMinutes(minute)

        console.log('in format date func, the time is: ', d)

        return d;
    }

你正在更新道具-这很糟糕

从props中的日期创建新日期

var newDate = new Date(props.date.date.getTime());
你的职能应该是:

const formatDate = (time) => {
        let hour = parseInt(time.substring(0,2)) // 13:51 -> 13
        let minute = parseInt(time.substring(3))
        let newDate = new Date(props.date.date.getTime());

        newDate.setHours(hour)
        newDate.setMinutes(minute)

        console.log('in format date func, the time is: ', newDate)

        return newDate;
    }

props.date.date
a
date
对象吗?如果是–它是可变的,因此当您调用
setHours
时,您可以更改它。您可以按照can You console.log中所述的方式克隆它。将输入也记录在setTimeAndDate函数顶部的startTime和endTime,以及formatDate函数中的prop.date(您应该将其作为参数传入,因为这是一个函数)并且提供的结果您不应该更新props-克隆日期:
var copiedDate=new date(props.date.date.getTime())道具和不变性:我不敢相信我忽略了这一点。非常感谢你。