' X'未定义 - 将React map调度发送到Props

时间:2017-07-31 15:19:37

标签: javascript reactjs

目前有一个问题,我希望根据' componentdidupdate'更新道具。但是每当我调用这个函数(onUpdateSelectedDate)时,它就会一直说

  

未定义onUpdateSelectedDate

我尝试了以下内容:

onUpdateSelectedDate(toggledDate)


this.onUpdateSelectedDate(toggledDate)


this.props.onUpdateSelectedDate(toggledDate)

并且仍然不确定我为什么会收到此错误。

以下代码

import DayPicker from "react-day-picker"
import React, {Component} from 'react'
import './calendarDatePicker.scss'
import propTypes from 'prop-types'
import { connect } from 'react-redux'

class CalendarDatePicker  extends Component {
  state = {
    toggledDate: null,
  }

  componentDidUpdate = () => {
    const toggledDate = this.state.toggledDate
    onUpdateSelectedDate(toggledDate)
  }

  render() {
    const selectedDate = this.props.selectedDays
    const onDayClick = this.props.onDayClick
    const toggledDate = this.state.toggledDate
    const modifiers = {
    }

    return (
        <DayPicker
          selectedDays={toggledDate===null ? selectedDate : toggledDate}
          onDayClick={onDayClick}
          todayButton="Go to Today"
          firstDayOfWeek={1}
          modifiers = {modifiers}
          onMonthChange={(d) => this.setState({toggledDate: d})}
        />
    )
  }
}

CalendarDatePicker.propTypes = {
  selectedDays: propTypes.instanceOf(Date),
  onDayClick: propTypes.func,
  onUpdateSelectedDate: propTypes.func,
}

const mapStateToProps = (state) => {
  return {
    //toggledDate: state.diaryContext.activities.selectedDates,
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    onUpdateSelectedDate: (toggledDate) => { dispatch(diaryActions.updateSelectedDate(toggledDate)) },
  }
}

export default connect(null, mapDispatchToProps)(CalendarDatePicker)

1 个答案:

答案 0 :(得分:2)

您对componentDidUpdate方法使用了错误的签名componentDidUpdate(prevProps, prevState),然后您就可以从mapStateToProps访问您的函数:

componentDidUpdate (prevProps, prevState) {
    const toggledDate = prevState.toggledDate
    prevProps.onUpdateSelectedDate(toggledDate)
}