繁体   English   中英

我不能将initialValues用于redux-form,该怎么办?

[英]I cannot use initialValues for redux-form, what should I do?

我想在我的组件中渲染两个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],
  };
}

希望它会有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM