我有一个TimePickerInput组件,就像这样:
当我在另一个组件中像这样使用它:
我经常会遇到这样的错误:
class TimePickerInput extends React.Component {
static propTypes = {
value: PropTypes.string,
onChange: PropTypes.func.isRequired,
disabled: PropTypes.bool
};
static defaultProps = {
onChange: function() {}
};
componentDidMount() {
this._$input
.timepicker({
autoclose: true,
minuteStep: 5,
showSeconds: false,
showMeridian: false
})
.on("changeTime.timepicker", e => {
this.props.onChange(e.time.value);
});
this._$input.timepicker("setTime", this.props.value);
}
componentWillReceiveProps(nextProps) {
this._$input.timepicker("setTime", nextProps.value);
}
render() {
const { disabled } = this.props;
return (
<Wrapper>
<IconWrapper>
<Icon className="fa fa-clock-o" />
</IconWrapper>
<Input
innerRef={ref => (this._$input = $(ref))}
type="text"
size="16"
className="form-control"
readOnly
disabled={disabled}
/>
</Wrapper>
);
}
}
export default TimePickerInput;
当我在另一个组件中像这样使用它:
<TimePickerInput value={notificationConfig.timeToSendAuditReminder} onChange={e => this.onChangeTimeField(e, 'timeToSendAuditReminder')}/>
并且需要在onChangeTimeField中进行如下更改:
onChangeTimeField = (value, fieldName) => {
this.props.dispatch(notificationConfigActions.requestUpdateTimeField(value, fieldName))
}
我经常会遇到这样的错误:
Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.
我找不到解决这个错误的方法。我认为它发生在 "on(“changeTime.timepicker”)" 和 "requestUpdateTimeField(value,fieldName)" 之间有很多onChange事件调用时。
setTime
时,jQuery插件是否可能触发changeTime.timepicker
事件?这会导致你的代码出现无限循环,因为最终在触发changeTime.timepicker
时会再次调用setTime
。你可以通过仅在e.time.value !== this.props.value
时调用TimePickerInput
中的onChange
处理程序来避免这种情况。 - TylerTimePickerInput
的onChange
回调函数来分派值,因此 UI 更新会调用onChange
回调函数,再次分派值并循环无限。尝试在分派前加入检查值是否已更改的代码。 - gonzofish