当前有一个问题,我想根据“ 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)
最佳答案
您为componentDidUpdate
方法使用了错误的签名,应该为componentDidUpdate(prevProps, prevState)
,然后可以从mapStateToProps
访问函数,如下所示:
componentDidUpdate (prevProps, prevState) {
const toggledDate = prevState.toggledDate
prevProps.onUpdateSelectedDate(toggledDate)
}