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

时间:2019-01-24 09:51:17

标签: javascript reactjs

我有一些数据正在传递通过道具,并将用于一张桌子,所以我可以显示整个工作日的营业时间和营业时间。

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

    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: []
}

谢谢!

2 个答案:

答案 0 :(得分:2)

调用this.state.scheduleTime方法之后,您不能检查setState的值并获得新值,因为尚未重新渲染组件。

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

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

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

答案 1 :(得分:1)

这是因为setState处于异步状态。它将立即设置,您可以使用回调程序。

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