我有一个无状态的React函数来呈现react-select Select to a form。除了redux-form被重置之外,其他一切都可以很好地使用redux-form。我需要在成功发布后手动重置表单。
当选择值发生更改时,onChange和onBlur会正确地更改redux-Form值。当我重置redux-form时,redux-form值被清除,但Select将具有旧值。
function SelectInput(props) {
const { input, options, label } = props;
const { onChange, onBlur } = input;
const handleChange = ({ value }) => {
onChange(value);
};
const handleBlur = ({ value }) => {
onBlur(value);
};
return (
<FormField {...props}>
<Select placeholder={label} options={options} onChange={handleChange} onBlur={handleBlur} />
</FormField>
);
}我将SelectInput转换为React.PureComponent,并将值作为组件内部的状态添加,并在组件收到新属性时进行查找:
constructor(props) {
super(props);
this.state = {value: ''}
}
componentWillReceiveProps(nextProps){
this.setState({value: nextprops.input.value})
}
<Select value={this.state.value} placeholder={label} options={options} onChange={handleChange} onBlur={handleBlur} />使用此选择根本无法显示该值。
问题是,当这个字段所属的redux-form被重置时,我如何更新Select以显示空值?Redux-form会在redux状态中相应地重置值,如果我尝试提交表单,验证会通知Select的值为空。但是,Select将显示旧值,这样用户就会认为选择了一个值。
重置是通过在实际的redux-form组件中调度重置来完成的。Redux devtools显示字段被重置,redux状态从所有值中清除,Select component不会将显示的值更新为空。
const afterSubmit = (result, dispatch) =>
dispatch(reset('datainputform'));
export default reduxForm({
form: 'datainputform',
onSubmitSuccess: afterSubmit,
})(DataInputForm);我使用的版本:
发布于 2018-06-02 03:19:51
让它起作用了。处理Select null值时出现问题。将无状态函数更改为PureComponent,并将值添加到状态。
constructor(props) {
super(props);
this.state = { value: '' };
}Redux-form通过发送新道具来更改react-select值。所以添加了
componentWillReceiveProps(nextProps) {
if (nextProps.input.value === '') {
this.setState({ value: '' });
}
}将setState添加到handleChange:
handleChange = (data) => {
const value = data === null ? '' : data;
this.setState({ value });
this.props.input.onChange(data.value);
};然后添加了价值道具。
<Select value={this.state.value}...发布于 2019-07-12 08:31:05
您还可以在表单级别本身设置密钥。键将采用一个唯一的值,您可以将该值存储在组件状态中。每次点击reset时,此唯一值都会更新。
state = {
unique_key: ''
}
// this is the onClick handler for reset button on the form
onResetForm = () => {
reset_val = Date.now();
this.props.reset();
this.setState({unique_key: reset_val});
}
<Form actions={action_func}, key={this.state.unique_key}/>现在,只要单击reset,处理程序就会更新unique_key。这将导致使用默认值重新呈现表单。处理程序还调用表单重置函数来清除redux。
https://stackoverflow.com/questions/50640858
复制相似问题