【问题标题】:Parent prop updating too late in React/ReduxReact/Redux 中的父属性更新太晚
【发布时间】:2019-08-24 09:32:37
【问题描述】:

我有一个调用两个子组件(child1.js、child2.js)的父组件(parent.js)。这一切都在一个选项卡上 - child1 基本上是在日历上添加事件的输入表单,而 child2 是日历。

从 child1 创建事件后,事件不会在日历上呈现,直到我单击另一个选项卡然后返回到该选项卡,或者我刷新页面。我的目标是,一旦创建了活动,日历应该会自动更新,而无需点击离开。

问题是,传递给 child2(事件数组)的道具没有按时更新。

这是 parent.js 的一小部分

const mapStateToProps = state => ({
  volunteers: selectors.volunteer.getAll(state)
})

changeState = () => {
  console.log("changing state in parent")
  this.setState({show: true})
}

render() => {
  <NewShift
    volunteers={this.props.volunteers}
    makeShift={this.props.makeShift}
  />
  <Index
    volunteers={this.props.volunteers}
  />
}

这是child1,这个函数在用户提交事件时调用。它为数据库添加了一个转变

  saveFood = () => {
    const volunteer = this.props.getVolunteer(this.state.formInputFields.id)
    this.props.makeShift({
      ...volunteer,
      shift: {
        role: volunteer.firstName,
        date: this.state.formInputFields.date,
        duration: 2,
        notes: this.state.formInputFields.notes
      }
    })
    this.props.changeState()
  }   

最后,这是 child2。我正在调用 componentDidUpdate() 来更新日历,但是 this.props.volunteers 不包含已成功添加到数据库中的最新事件。

    componentDidUpdate() {

        console.log("Updated")
        const calendar = this.state.c

        /* Removes all events from calendar */
        const events = calendar.getEvents()
        for(var x = 0; x < events.length; x++) {
            calendar.getEventById(events[x].id).remove()
        }


        /* Re-renders all events on calendar */
        var volunteers = this.props.volunteers
        for(var i = 0; i < volunteers.length; i++) {
            var shift = volunteers[i].shift

            for(var j = 0; j < shift.length; j++) {
                calendar.addEvent({
                    id: j,
                    title: volunteers[i].firstName + ' ' + volunteers[i].lastName,
                    start: new Date(shift[j].date + 'T00:00:00'),
                    notes: shift[j].notes
                })
            }
        }
    }

【问题讨论】:

  • 数据库是什么意思?你从哪里获取这个数据库中的值到 react 应用程序?

标签: javascript react-redux


【解决方案1】:

我会调查componentDidUpdate()documentation。这个函数有两个参数componentDidUpdate( prevProps, prevState )在这个函数中你可以比较this.propsprevProps。如果两者之间有变化,则执行更新组件的逻辑。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    • 2020-11-27
    • 1970-01-01
    • 2017-05-14
    • 2019-01-16
    • 2017-10-16
    相关资源
    最近更新 更多