我的代码使用条件渲染从表单DOM中删除字段。对于redux表单,已删除的字段值将保留在表单存储中,这确实很烦人。任何人都有好主意如何解决此问题?以下是我对条件渲染的实现。因为在我的项目中进行条件渲染是很常见的,所以如何才能轻松解决问题?
import React from "react";
import { connect } from "react-redux";
import { Field, getFormValues } from "redux-form";
import { Grid, Form } from "semantic-ui-react";
import RenderFieldSelect from "../../formElements/Select";
import {
PROPERTY_TYPE_1,
PROPERTY_TYPE_2,
SUB_TYPE,
EMPTY_OPTIONS
} from "./SelectOptions";
import { required } from "redux-form-validators";
import { withRouter } from "react-router";
class SummaryAttributes extends React.Component {
render() {
let propertyType; // property type
let propertyTypes = EMPTY_OPTIONS; // propertyTypes options
let hasSubType;
let subTypes = EMPTY_OPTIONS;
const { formValues } = this.props;
if (formValues !== undefined) {
const { scorecardType } = this.props.match.params;
switch (scorecardType) {
case "1":
propertyTypes = PROPERTY_TYPE_1;
break;
case "2":
propertyTypes = PROPERTY_TYPE_2;
break;
default:
}
propertyType = formValues.propertyType;
switch (propertyType) {
case "1":
subTypes = SUB_TYPE;
hasSubType = true;
break;
case "2":
hasSubType = false;
break;
default:
subTypes = SUB_TYPE;
hasSubType = true;
}
}
return (
<div>
<Grid>
<Grid.Row columns="equal">
<Grid.Column>
<Form.Group widths="equal">
<Field
name="propertyType"
component={RenderFieldSelect}
label="Property Type"
required="Y"
options={propertyTypes}
validate={[required()]}
/>
</Form.Group>
</Grid.Column>
<Grid.Column>
{hasSubType && (
<Field
name="subType"
component={RenderFieldSelect}
label="Sub Type"
required="Y"
options={subTypes}
validate={[required()]}
/>
)}
</Grid.Column>
</Grid.Row>
</Grid>
</div>
);
}
}
const mapStateToProps = state => ({
formValues: getFormValues("propertyForm")(state)
});
export default withRouter(
connect(
mapStateToProps,
null
)(SummaryAttributes)
);
Reducer:Index.js
import { combineReducers } from 'redux';
import { reducer as formReducer } from 'redux-form';
import loadingReducer from './reducer_loading';
export default combineReducers({
form: formReducer,
loading: loadingReducer
});
谢谢。
答案 0 :(得分:0)
我找到了解决此问题的方法:
import { combineReducers } from "redux";
import {
reducer as formReducer,
actionTypes as formActionTypes
} from "redux-form";
const removeUnregisteredFormFieldValue = (state, action) => {
if (action.type !== formActionTypes.UNREGISTER_FIELD) return state;
const {
values: { [action.payload.name]: unregistered, ...values }
} = state;
return { ...state, values };
};
export default combineReducers({
form: formReducer.plugin({
sampleForm: removeUnregisteredFormFieldValue,
propertyForm: removeUnregisteredFormFieldValue
})
});