React Hook useState setter for prop失败

时间:2019-10-03 08:50:12

标签: reactjs react-hooks

我将missingWeekDays初始化为一个空数组[]。我创建了一个字符串数组weekdays并分配给missingWeekDays。但是当我退出控制台时,weekdays有内容,但是missingWeekDays仍然为空。为什么会这样?

有人建议setMissingWeekDays应该具有像旧setState一样的回调。但是我在此回调中找不到任何文档...链接将不胜感激!

import React, { FC, useEffect, useState } from 'react'

const Component: FC = () => {

    const initialStart = moment()
        .year(2018)
        .week(5)
        .startOf('isoWeek')

    const [missingWeekDays, setMissingWeekDays] = useState<string[]>([])
    const [startDate, setStartDate] = useState(initialStart)

    useEffect(() => {
        const weekdays = createWeekdaysList(startDate.toDate())
        setMissingWeekDays(weekdays)
        console.log(missingWeekDays, weekdays)
    }, [startDate])

    return <CigarettesDetails onTimeChange={handleTimeChange} data={data} />
}

export default CigarettesDetailsContainer

const createWeekdaysList = (startDate: Date): string[] => {
    const weekdaysList: string[] = []

    let weekDay = 0
    while (weekDay < 7) {
        const date: string = moment(startDate)
            .clone()
            .add(weekDay, 'day')
            .format('YYYY-MM-DD')

        weekdaysList.push(date)
        weekDay += 1
    }

    return weekdaysList
}

1 个答案:

答案 0 :(得分:0)

您来自useState的设置器被异步处理。这将导致您的控制台日志中没有更新的数据。该线程为您添加更多颜色:

useState set method not reflecting change immediately