如何正确实现 onBlur 以分派 API 并更新组件中的道具而不在渲染方法上创建循环?
How to correctly implement onBlur to dispatch API and update props in a component without creating loop on render method?
我在 Ant.Design 中的输入字段 onBlur/onChange 上调用 API(基于 React redux)。在调用 API 时,它会更新组件的道具,并在更新道具时调用渲染方法。在 render 方法中,它重新渲染 UI 并再次调用 onBlur/onChange,它陷入了无限循环。
我已尝试将其维持在该状态,但它并没有停止这种递归行为。
render () {
const {
form: { getFieldDecorator, getFieldValue }, payload: { payload },
} = this.props;
console.log(" Client details " + JSON.stringify(this.props));
return ( <Form onSubmit={this.handleSubmit} hideRequiredMark style={{ marginTop: 8 }}>
<FormItem {...formItemLayout} label={<FormattedMessage id="form.seller.code" />}>
{getFieldDecorator('code', {
rules: [
{
required: true,
message: formatMessage({ id: 'validation.code.required' }),
},
],
})(<Input placeholder={formatMessage({ id: 'form.code.placeholder' })}
onChange={this.fetchDetails()}
/>)}
</FormItem>
</Form>
)
}
fetchDetails() {
const { dispatch, form } = this.props;
const value = this.props.form.getFieldValue('code');
dispatch({
type: 'form/fetchDetails',
payload: value,
});
}
预期结果:只获取一次详细信息
实际:重复调用 onBlur 和 render 方法导致卡在循环中。
您正在将 this.fetchDetails()
(函数调用)传递给 onChange,而您应该将 this.fetchDetails
(函数引用)传递给它。
我在 Ant.Design 中的输入字段 onBlur/onChange 上调用 API(基于 React redux)。在调用 API 时,它会更新组件的道具,并在更新道具时调用渲染方法。在 render 方法中,它重新渲染 UI 并再次调用 onBlur/onChange,它陷入了无限循环。
我已尝试将其维持在该状态,但它并没有停止这种递归行为。
render () {
const {
form: { getFieldDecorator, getFieldValue }, payload: { payload },
} = this.props;
console.log(" Client details " + JSON.stringify(this.props));
return ( <Form onSubmit={this.handleSubmit} hideRequiredMark style={{ marginTop: 8 }}>
<FormItem {...formItemLayout} label={<FormattedMessage id="form.seller.code" />}>
{getFieldDecorator('code', {
rules: [
{
required: true,
message: formatMessage({ id: 'validation.code.required' }),
},
],
})(<Input placeholder={formatMessage({ id: 'form.code.placeholder' })}
onChange={this.fetchDetails()}
/>)}
</FormItem>
</Form>
)
}
fetchDetails() {
const { dispatch, form } = this.props;
const value = this.props.form.getFieldValue('code');
dispatch({
type: 'form/fetchDetails',
payload: value,
});
}
预期结果:只获取一次详细信息 实际:重复调用 onBlur 和 render 方法导致卡在循环中。
您正在将 this.fetchDetails()
(函数调用)传递给 onChange,而您应该将 this.fetchDetails
(函数引用)传递给它。