我将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
}
答案 0 :(得分:0)
您来自useState的设置器被异步处理。这将导致您的控制台日志中没有更新的数据。该线程为您添加更多颜色: