我正在学习React和Redux。我陷入了react-dates组件与Redux的连接。主要问题是, 某物 (可能是react-dates)会在应用程序启动时触发redux操作(SET_START_DATE,SET_END_DATE),即使这些操作应该在我点击后发生日历中的日期。因此,我得到了这些错误:
Failed prop type: Invalid input type: `startDate` of type `string`
supplied to `withStyles(DateRangePicker)`, expected `object`.
Failed prop type: Invalid input type: `endDate` of type `string`
supplied to `withStyles(DateRangePicker)`, expected `object`.
Uncaught TypeError: date.format is not a function
带有DatePicker的组件代码:
import 'react-dates/initialize';
import 'react-dates/lib/css/_datepicker.css';
import React, {Component} from 'react';
import {connect} from 'react-redux';
import {DateRangePicker} from 'react-dates'
import {setEndDate, setStartDate} from "../actions/filters";
class Filters extends Component {
state = {
calendarFocused: null
};
onDatesChange = ({startDate, endDate}) => {
this.props.setStartDate(startDate);
this.props.setEndDate(endDate);
};
onFocusChange = (calendarFocused) => {
this.setState(() => ({calendarFocused}));
};
render() {
return (
<div>
{
<DateRangePicker
startDateId="startDate"
endDateId="endDate"
startDate={this.props.startDate}
endDate={this.props.endDate}
onDatesChange={this.onDatesChange}
focusedInput={this.state.calendarFocused}
onFocusChange={this.onFocusChange}
showClearDates={true}
numberOfMonths={1}
isOutsideRange={() => false}
/>
}
</div>
);
}
}
function mapStateToProps(state) {
return {
startDate: state.filters.startDate,
endDate: state.filters.endDate
};
}
function mapDispatchToProps(dispatch) {
return {
setStartDate: (startDate) => dispatch(setStartDate(startDate)),
setEndDate: (endDate) => dispatch(setEndDate(endDate)),
};
}
export default connect(mapStateToProps, mapDispatchToProps)(Filters);
动作:
// SET_START_DATE
export const setStartDate = (startDate) => ({
type: 'SET_START_DATE',
startDate
});
// SET_END_DATE
export const setEndDate = (endDate) => ({
type: 'SET_END_DATE',
endDate
});
减速器:
import moment from 'moment';
const filtersReducerDefaultState = {
startDate: moment().startOf('month'),
endDate: moment().endOf('month')
};
export default (state = filtersReducerDefaultState, action) => {
switch (action.type) {
case 'SET_START_DATE': {
console.log(action.startDate);
return {
...state,
startDate: action.startDate
}
}
case 'SET_END_DATE': {
return {
...state,
endDate: action.endDate
}
}
default:
return state;
}
};
我正在使用以下依赖项: