我想在我的组件中渲染两个 redux 表单Fields
。
对于来自对服务器的调用的那些字段,我有一些初始值。但我不能在mapStateToProps
中使用initialValues
.
为什么?因为我的应用状态是一个实体数组,它位于我有权访问this.entityId
的组件中,这使我可以从该数组中选择正确的实体。在mapStateToProps
我无法访问this
在这种情况下我该怎么办?
class ShowGroup extends Component {
constructor(props) {
super(props);
this.groupId = this.props.match.params.id;
this.state = {
loading: true,
error: null
};
}
componentDidMount() {
this.props.fetchGroup(this.groupId,
() => this.setState({loading: false}),
error => this.setState({loading:false, error: error})
);
}
render() {
let {props, state} = this;
let group = props.groups[this.groupId];
return (
<div className="show-group">
<form>
<Field
name="name"
fieldType="input"
type="text"
component={renderField}
label="Name"
validate={validateName}
/>
<Field
name="description"
fieldType="textarea"
component={renderField}
label="Name"
rows="2"
validate={validateName}
onBlur={this._updateGroupDesc}
/>
</form>
</div>
);
}
}
function mapStateToProps(state) {
return {
groups: state.groups
};
}
const mapDispatchToProps = (dispatch) => {
return {
fetchGroup: (groupId, successCallback, errorCallback) => dispatch(fetchGroup(groupId, successCallback, errorCallback))
};
};
export default connect(mapStateToProps, mapDispatchToProps)(reduxForm({
validate,
enableReinitialize: true,
form:'ShowGroup'
})(ShowGroup));
您可以在 mapStateToProps
中使用第二个参数 - ownProps
。
因此,您可以在此函数中访问组件的道具。
例如:
function mapStateToProps(state, ownProps) {
const groupId = ownProps.match.params.id;
return {
groups: state.groups,
initialValues: state.groups[groupId],
};
}
希望它能有所帮助。