如何在redux表单上设置init值

时间:2018-03-15 15:24:16

标签: reactjs redux-form

我正在尝试在redux表单加载上设置init值,但它对我不起作用。我已经尝试了here的所有3个选项。我在dispatch中尝试了initializecomponentDidMount。也尝试在课堂底部的出口部分。这个我不知道怎么把它放在connect部分,因为我正在使用地图功能。我把它放在form部分

    class SecurityExemptionsNew extends Component {
    constructor(props) {
        super(props);

        this.renderSelectField = this.renderSelectField.bind(this);
        this.renderTextField = this.renderTextField.bind(this);

        this.renderSelect2Field = this.renderSelect2Field.bind(this);

        this.runOnce = false;
        this.state = {
            loaded: false,
            isLoading: true,
            searchable: true,
            selectValue: { value: '0', label: 'All'},
            selectMarketValue : "Group Enterprise Technology (GET)",
            clearable: true,
            rtl: false,
            options: [
                { value: '0', label: 'All'}
                ],
            toggleChecked: true,
            lm_security_engineer: ''
        };

    }

    omponentDidMount() {
        this.passMetaBack;
        this.props.dispatch(change('SecurityExemptionsNewForm', 'market', 'Group Enterprise Technology (GET)'));
        this.props.initialize({ market: 'Group Enterprise Technology (GET)' });
    }


    renderSelectField(field) {

        let options = [];
        if (field.label == 'Type') {
            options = this.populateOptions(this.exemptionType, 'name', 'name');
        } else if (field.label == 'Market') {
            options = this.populateOptions(this.markets, 'name', 'name');
        } else if (field.label == 'Service Domain') {
            options = this.populateOptions(this.serviceDomain, 'name', 'name');
        } else if (field.label == 'Service/Project/Programme') {
            options = this.populateOptions(this.servicesList, 'id', 'name');
            options.unshift(
                <option key="0" value="0" selected>
                    All
                </option>
            );
        } else if (field.label == 'Comms Matrix') {
            options.unshift(
                <option key="0" value="0" selected>
                    All
                </option>
            );
        } else if (field.label == 'Security Engineer') {
            options = this.populateOptions(this.securityEngineerList, 'email', 'email');
            options.unshift(
                <option key="0" value="" selected>
                    --Select Engineer--
                </option>
            );
        } else if (field.label == 'LM Security Engineer') {
            options = this.populateOptions(this.securityEngineerLocalMarketList, 'email', 'email');
            options.unshift(
                <option key="0" value="" selected>
                    --Select Engineer--
                </option>
            );
        } else if (field.label == 'Business Priority') {
            options = this.populateOptions(this.businessPriority, 'name', 'name');
        }
        let id = "select_" + field.input.name;
        return (
            <div className="form-group">
                <label className="control-label col-sm-2">{field.label}</label>
                <div className="col-sm-10">
                    <select
                        id={id}
                        {...field.select}
                        name={field.input.name}
                        className="form-control form-control-inline"
                        type="select"
                        onChange={event => {
                              //props.input.onChange(event); // <-- Propagate the event
                              this.updateCommsMatrix(event.target.value);
                            }}
                    >
                        {options}
                    </select>
                </div>
            </div>
        );
    }

    renderSelect2Field(field){
        return(
                <div className="form-group">
                    <label className="control-label col-sm-2">{field.label}</label>
                    <div className="col-sm-4">

                        <Async 
                            name={field.input.name}
                            multi={false} 
                            value={this.state.selectValue} 
                            onChange={this.updateValue} 
                            valueKey="value" 
                            labelKey="label" 
                            loadOptions={this.getCommsmatrices} 
                            onValueClick={this.gotoCommsmatrix}
                            cache={false}
                            isLoading={this.state.isLoading}
                            optionRenderer={(option) => {return option.label;}}
                        />
                    </div>
                </div>
        );
    }

    render() {
        console.log(this);
        if (!this.runOnce && this.props.isReady) {
            this.runOnce = true;
            this.initData();
        }
        const { handleSubmit } = this.props;
        let form = 'Loading...';
        if (this.state.loaded) {
            let policiesTable = this.renderPolicies();
            return (
                <div className="container-fluid">
                    <form onSubmit={handleSubmit} className="form-horizontal">
                        <Field
                            label="Type"
                            loadFrom="exemptionType"
                            name="exemption_type"
                            component={this.renderSelectField}
                        />
                        <Field
                            label="Market"
                            loadFrom="markets"
                            name="market"
                            component={this.renderSelectField}
                        />
                        <Field
                            label="Service Domain"
                            loadFrom="serviceDomain"
                            name="service_domain"
                            component={this.renderSelectField}
                            type="select"
                        />
                        <Field
                            label="Service/Project/Programme"
                            loadFrom="servicesList"
                            name="service_id"
                            component={this.renderSelectField}
                            type="select"
                        />

                        <Field
                            label="Demand Ref"
                            name="demand_ref"
                            component={this.renderTextField}
                            type="text"
                        />
                        <Field
                            label="Exemption Summary"
                            name="name"
                            component={this.renderTextField}
                            type="text"
                        />
                        <Field
                            label="Exemption Description"
                            name="description"
                            component={this.renderTextareaField}
                            type="textarea"
                        />
                        <div className="form-group">
                            <label className="control-label col-sm-2">Comms Matrix:</label>
                            <div className="col-sm-4">

                                <Async 
                                    multi={false} 
                                    value={this.state.selectValue} 
                                    onChange={this.updateValue} 
                                    valueKey="value" 
                                    labelKey="label" 
                                    loadOptions={this.getCommsmatrices} 
                                    onValueClick={this.gotoCommsmatrix}
                                    cache={false}
                                />
                            </div>
                        </div>
                        {policiesTable}
                        <Field
                            label="Requestor"
                            name="requestor"
                            component={this.renderTextField}
                            type="text"
                            readonly="readonly"
                        />
                        <Field
                            label="Security Engineer"
                            loadFrom="securityEngineerList"
                            name="security_engineer"
                            component={this.renderSelectField}
                            type="select"
                        />
                        {this.state.lm_security_engineer}
                        <Field
                            label="Link to Design Doc"
                            name="designdoc"
                            component={this.renderTextField}
                            type="text"
                        />
                        <Field
                            label="Business Priority"
                            loadFrom="businessPriority"
                            name="business_priority"
                            component={this.renderSelectField}
                            type="select"
                        />
                        <Field
                            label="Expiry date (dd-MMM-yy)"
                            name="expiry_date"
                            component={this.renderTextField}
                            type="text"
                        />
                        <div className="form-group">
                            <div className="col-sm-offset-2 col-sm-10">
                                <button id="btnSubmit" type="submit" name="btnSubmit" className="btn btn-vodafone hidden-print">Submit</button>
                            </div>
                        </div>
                    </form>
                </div>
            );
        }

        return <div className="container-fluid">{form}</div>;
    }
}

function mapStateToProps(state) {
    return {
        securityExemptions: state.securityExemptions,
        commsmatrices: state.commsmatrices
    };
}

//Anything returned from this function will end up as props
//on the User container
function mapDispatchToProps(dispatch) {
    // Whenever getUser is called, the result should be passed
    // to all our reducers
    //return {
    //actions: bindActionCreators(Object.assign({}, fetchServices, checkServiceEditable ), dispatch)
    //};
    return bindActionCreators(
        {
            fetchExemptionType,
            fetchMarkets,
            fetchServiceDomains,
            fetchServicesList,
            fetchCommsmatricesByService,
            fetchExemptionsForCommsmatrix,
            fetchSecurityEngineerList,
            fetchBusinessPriorityList
        },
        dispatch
    );
}

SecurityExemptionsNew = connect(mapStateToProps, mapDispatchToProps)(
    SecurityExemptionsNew
);

//Decorate the form component
export default reduxForm({
    form: 'SecurityExemptionsNewForm', // a unique name for this form
    initialValues: { service_domain: 'Corporate (Internal/External)' }
})(SecurityExemptionsNew);

更新

由于无法使用redux-form初始化默认值,我只使用default values标记state

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import FontAwesome from 'react-fontawesome';
import { isServiceName, isServiceRef } from '../../scripts/validation';
import {
    fetchExemptionType,
    fetchMarkets,
    fetchServiceDomains,
    fetchServicesList,
    fetchExemptionsForCommsmatrix,
    fetchSecurityEngineerList,
    fetchBusinessPriorityList
} from '../../actions/security';
import { fetchCommsmatricesByService } from '../../actions/commsmatrices';
import axios from 'axios';
import { Field, reduxForm, change } from 'redux-form';
import PropTypes from 'prop-types';
import { Select, Async } from "react-select";
import 'react-select/dist/react-select.css';

class SecurityExemptionsNew extends Component {
    constructor(props) {
        super(props);
        this.handleSaveBtnClick = this.handleSaveBtnClick.bind(this);
        this.handleShowError = this.handleShowError.bind(this);
        this.initData = this.initData.bind(this);
        this.renderSelectField = this.renderSelectField.bind(this);
        this.renderTextField = this.renderTextField.bind(this);
        this.updateCommsMatrix = this.updateCommsMatrix.bind(this);
        this.renderSelect2Field = this.renderSelect2Field.bind(this);
        this.clearValue = this.clearValue.bind(this);
        this.updateValue = this.updateValue.bind(this);
        this.getCommsmatrices = this.getCommsmatrices.bind(this);
        this.fnToggleCheckboxes = this.fnToggleCheckboxes.bind(this);
        this.handleCheckedValues = this.handleCheckedValues.bind(this);
        this.meta = {
            title: 'Request Exemption',
            description: 'This section allows you to request an exemption'
        };
        this.passMetaBack = this.passMetaBack.bind(this);
        this.runOnce = false;
        this.state = {
            loaded: false,
            isLoading: true,
            searchable: true,
            selectValue: { value: '0', label: 'All'},
            selectMarketValue : "Group Enterprise Technology (GET)",
            clearable: true,
            rtl: false,
            options: [
                { value: '0', label: 'All'}
                ],
            toggleChecked: true,
            lm_security_engineer: '',
            select_exemption_type: 'Security',
            select_market: 'Group Enterprise Technology (GET)',
            select_service_domain: 'Corporate (Internal/External)',
            select_service_id: '0',
            select_security_engineer: null,
            select_business_priority: 'Low'
        };
        this.exemptionType = {};
        this.markets = {};
        this.serviceDomain = {};
        this.servicesList = {};
        this.matrices = {};
        this.securityEngineerList = {};
        this.securityEngineerLocalMarketList = {}
        this.businessPriority = {}
        this.tableOptions = {
                paginationShowsTotal: false,
                sizePerPageList: [ {
                    text: '10', value: 10
                  }, {
                    text: '50', value: 50
                  }, {
                      text: '100', value: 100
                    } 
                  ],
            };
        this.checkedValues = [];
    }

    componentDidMount() {
        console.log("componentDidMount");
        this.passMetaBack;
        this.props.initialize({ market: 'Group Enterprise Technology (GET)' });
        this.props.dispatch(change('SecurityExemptionsNewForm', 'market', 'Group Enterprise Technology (GET)'));
    }

    passMetaBack = () => {
        this.props.passMetaBack(this.meta);
    };

    renderSelectField(field) {
        let defaultValue = this.state['select_'+field.input.name];
        let options = [];
        if (field.label == 'Type') {
            options = this.populateOptions(this.exemptionType, 'name', 'name');
        } else if (field.label == 'Market') {
            options = this.populateOptions(this.markets, 'name', 'name');
        } else if (field.label == 'Service Domain') {
            options = this.populateOptions(this.serviceDomain, 'name', 'name');
        } else if (field.label == 'Service/Project/Programme') {
            options = this.populateOptions(this.servicesList, 'id', 'name');
            options.unshift(
                <option key="0" value="0">
                    All
                </option>
            );
        } else if (field.label == 'Comms Matrix') {
            options.unshift(
                <option key="0" value="0">
                    All
                </option>
            );
        } else if (field.label == 'Security Engineer') {
            options = this.populateOptions(this.securityEngineerList, 'email', 'email');
            options.unshift(
                <option key="0" value="">
                    --Select Engineer--
                </option>
            );
        } else if (field.label == 'LM Security Engineer') {
            options = this.populateOptions(this.securityEngineerLocalMarketList, 'email', 'email');
            options.unshift(
                <option key="0" value="">
                    --Select Engineer--
                </option>
            );
        } else if (field.label == 'Business Priority') {
            options = this.populateOptions(this.businessPriority, 'name', 'name');
        }
        let id = "select_" + field.input.name;
        return (
            <div className="form-group">
                <label className="control-label col-sm-2">{field.label}</label>
                <div className="col-sm-10">
                    <select
                        id={id}
                        {...field.select}
                        name={field.input.name}
                        className="form-control form-control-inline"
                        type="select"
                        onChange={event => {
                              //props.input.onChange(event); // <-- Propagate the event
                              this.updateCommsMatrix(event.target.value);
                            }}
                        defaultValue={defaultValue}
                    >
                        {options}
                    </select>
                </div>
            </div>
        );
    }

    renderSelect2Field(field){
        return(
                <div className="form-group">
                    <label className="control-label col-sm-2">{field.label}</label>
                    <div className="col-sm-4">

                        <Async 
                            name={field.input.name}
                            multi={false} 
                            value={this.state.selectValue} 
                            onChange={this.updateValue} 
                            valueKey="value" 
                            labelKey="label" 
                            loadOptions={this.getCommsmatrices} 
                            onValueClick={this.gotoCommsmatrix}
                            cache={false}
                            isLoading={this.state.isLoading}
                            optionRenderer={(option) => {return option.label;}}
                        />
                    </div>
                </div>
        );
    }

    renderTextField(field) {
        let value = '';
        let readonly = false
        if (field.label == 'Requestor') {
            value = this.props.activeUser.email;
            readonly = true;
        }
        return (
            <div className="form-group">
                <label className="control-label col-sm-2">{field.label}</label>
                <div className="col-sm-10">
                    <input
                        name={field.input.name}
                        className="form-control form-control-inline"
                        type="text"
                        {...field.text}
                        defaultValue={value}
                        readOnly={readonly}
                    />
                </div>
            </div>
        );
    }

    renderTextareaField(field) {
        return (
            <div className="form-group">
                <label className="control-label col-sm-2">{field.label}</label>
                <div className="col-sm-10">
                    <textarea
                        name={field.input.name}
                        className="form-control form-control-inline"
                        type="textarea"
                        {...field.text}
                    />
                </div>
            </div>
        );
    }

    handleCheckedValues({target}){
        if (target.checked){        
            target.setAttribute('checked', true);
            this.checkedValues.push({id:$(target).val()});
        }else{
            target.removeAttribute('checked');
            let arr = this.checkedValues.filter(function(item) { 
                return item.id !== $(target).val()
            })
            this.checkedValues = arr;
        }
    }

    render() {
        console.log(this);
        if (!this.runOnce && this.props.isReady) {
            this.runOnce = true;
            this.initData();
        }
        const { handleSubmit } = this.props;
        let form = 'Loading...';
        if (this.state.loaded) {
            let policiesTable = this.renderPolicies();
            return (
                <div className="container-fluid">
                    <form onSubmit={handleSubmit} className="form-horizontal">
                        <Field
                            label="Type"
                            loadFrom="exemptionType"
                            name="exemption_type"
                            component={this.renderSelectField}
                        />
                        <Field
                            label="Market"
                            loadFrom="markets"
                            name="market"
                            component={this.renderSelectField}
                        />
                        <Field
                            label="Service Domain"
                            loadFrom="serviceDomain"
                            name="service_domain"
                            component={this.renderSelectField}
                            type="select"
                        />
                        <Field
                            label="Service/Project/Programme"
                            loadFrom="servicesList"
                            name="service_id"
                            component={this.renderSelectField}
                            type="select"
                        />

                        <Field
                            label="Demand Ref"
                            name="demand_ref"
                            component={this.renderTextField}
                            type="text"
                        />
                        <Field
                            label="Exemption Summary"
                            name="name"
                            component={this.renderTextField}
                            type="text"
                        />
                        <Field
                            label="Exemption Description"
                            name="description"
                            component={this.renderTextareaField}
                            type="textarea"
                        />
                        <div className="form-group">
                            <label className="control-label col-sm-2">Comms Matrix:</label>
                            <div className="col-sm-4">

                                <Async 
                                    multi={false} 
                                    value={this.state.selectValue} 
                                    onChange={this.updateValue} 
                                    valueKey="value" 
                                    labelKey="label" 
                                    loadOptions={this.getCommsmatrices} 
                                    onValueClick={this.gotoCommsmatrix}
                                    cache={false}
                                />
                            </div>
                        </div>
                        {policiesTable}
                        <Field
                            label="Requestor"
                            name="requestor"
                            component={this.renderTextField}
                            type="text"
                            readonly="readonly"
                        />
                        <Field
                            label="Security Engineer"
                            loadFrom="securityEngineerList"
                            name="security_engineer"
                            component={this.renderSelectField}
                            type="select"
                        />
                        {this.state.lm_security_engineer}
                        <Field
                            label="Link to Design Doc"
                            name="designdoc"
                            component={this.renderTextField}
                            type="text"
                        />
                        <Field
                            label="Business Priority"
                            loadFrom="businessPriority"
                            name="business_priority"
                            component={this.renderSelectField}
                            type="select"
                        />
                        <Field
                            label="Expiry date (dd-MMM-yy)"
                            name="expiry_date"
                            component={this.renderTextField}
                            type="text"
                        />
                        <div className="form-group">
                            <div className="col-sm-offset-2 col-sm-10">
                                <button id="btnSubmit" type="submit" name="btnSubmit" className="btn btn-vodafone hidden-print">Submit</button>
                            </div>
                        </div>
                    </form>
                </div>
            );
        }

        return <div className="container-fluid">{form}</div>;
    }
}

function mapStateToProps(state) {
    return {
        securityExemptions: state.securityExemptions,
        commsmatrices: state.commsmatrices
    };
}

//Anything returned from this function will end up as props
//on the User container
function mapDispatchToProps(dispatch) {
    // Whenever getUser is called, the result should be passed
    // to all our reducers
    //return {
    //actions: bindActionCreators(Object.assign({}, fetchServices, checkServiceEditable ), dispatch)
    //};
    return bindActionCreators(
        {
            fetchExemptionType,
            fetchMarkets,
            fetchServiceDomains,
            fetchServicesList,
            fetchCommsmatricesByService,
            fetchExemptionsForCommsmatrix,
            fetchSecurityEngineerList,
            fetchBusinessPriorityList
        },
        dispatch
    );
}

SecurityExemptionsNew = connect(mapStateToProps, mapDispatchToProps)(
    SecurityExemptionsNew
);

function validate (values) {
    console.log(values);
    const errors = {};

    if(!values.name){
        errors.name = "Enter summary";
    }

    return errors;
}

//Decorate the form component
export default reduxForm({
    form: 'SecurityExemptionsNewForm', // a unique name for this form
    validate,
    initialValues: { market: 'Group Enterprise Technology (GET)', service_domain: 'Corporate (Internal/External)' }
})(SecurityExemptionsNew);

0 个答案:

没有答案