React Hook useState setter for prop fails



我将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
}

来自 useState 的 setter 是异步处理的。这会导致控制台日志没有更新的数据。此线程为您添加更多颜色:

使用状态集方法不立即反映更改

相关内容

  • 没有找到相关文章

最新更新