gpt4 book ai didi

javascript - Object.keys 映射不起作用后设置状态

转载 作者:行者123 更新时间:2023-11-28 17:11:15 25 4
gpt4 key购买 nike

我有一段数据正在通过 props 传递,并将用于表格,这样我就可以显示整个工作日的营业时间和营业时间。

这里的问题是我无法以我创建的状态保存此信息。我在这里做错了什么?

    constructor(props) {
super(props);

this.state = {
weekDays: moment.weekdays(true),
scheduleTime: []
}
}

componentDidMount() {
const openingSchedule = this.props.operationDays; //data passed by props
console.log(openingSchedule);

let scheduleTime;
console.log('1', scheduleTime)

Object.keys(openingSchedule).map(key => { //obj through a map
console.log('week day',key) //logs a week day, between monday and sunday
console.log('schedule for ' + key, openingSchedule[key]) //logs OpenHours {endTime: '23:00', startTime: '08:00'}

if (openingSchedule[key] && openingSchedule[key].startTime) {
scheduleTime = openingSchedule[key].startTime;
console.log('2', scheduleTime) // logs 08:00
}
})

console.log('3', scheduleTime)
this.setState({
scheduleTime: scheduleTime
})
console.log('4', this.state.scheduleTime) //logs scheduleTime: []
}

谢谢!

最佳答案

您无法在调用 setState 方法后立即检查 this.state.scheduleTime 的值并获取新值,因为您的组件尚未重新渲染还没有。

this.setState({
scheduleTime: scheduleTime
})
console.log('4', this.state.scheduleTime) //logs scheduleTime: []

或者你在componentDidUpdate方法中检查新值,或者你可以这样写:

this.setState({
scheduleTime: scheduleTime
}, () => console.log('4', this.state.scheduleTime))

关于javascript - Object.keys 映射不起作用后设置状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54343706/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com