redux-form如何加载数据进行编辑

时间:2017-02-03 10:47:25

标签: javascript reactjs react-redux redux-form

我正在使用redux-form,我似乎很难加载编辑表单的初始数据,但数据未在提交时验证。我已设法将数据传递并加载到字段中,但似乎没有加载到表单道具等中。请参阅以下代码段,如果需要更多内容,请告诉我。

Form_Bayan.js

import React, {Component, PropTypes} from "react";  
import {browserHistory} from "react-router";        
import {reduxForm, Field} from "redux-form";

import {MyCustomInput, MySimpleInput, MyCustomSelect} from "./__form_field_components";

import {connect} from "react-redux";
import {bindActionCreators} from "redux";
import {
    ADMIN_FETCH_AUTOSUGGESTS_Lbl,
    adminFetchAutoSuggestCats_act,
    ADMIN_GETCATID_BYNAME_Lbl,
    adminGetCatIdByName_act,
    ADMIN_ADDNEWBAYAAN_Lbl,
    adminAddNewBayaan_act,
    adminFetchArticlesByCat_act,
    adminUpdateBayaan_act
} from "../../actions/adminActionCreators";
import _ from "lodash";


class NewBayanForm extends Component {

    constructor(props) {
        super(props);       

        this.state = {
            submitButtonMeta: {
                btnTitle: "Save",
                btnClass: "btn btn-default",
                btnIcon: null,
                disabled: false
            },
            globalMessage: {                        // set when an action is performed by ActionCreation+Reducer and a message is returned
                message: "",
                className: ""
            },
            tempData: {

                the_bayaansMainCat_id: this.props.associatedMainCatId,              // being passed from parent component to avoide redundent declaration
                the_autoSuggestCatList: [],
                slug: "",
                the_catId: null
            }
        };
    }

    resetMessageState() {
        var noMsg = {message: "", className: ""};
        this.setState({globalMessage: noMsg});
    }

    componentDidMount() {
        this.props.adminFetchAutoSuggestCats_act(this.state.tempData.the_bayaansMainCat_id);
    }

    doSubmit(props) {

        var newBayanObj = {
            item_title: props.titleTxt,
            item_slug: this.state.tempData.slug,
            content: props.videoIdTxt,
            picture: "",
            attachment: "",
            media_path: "https://www.youtube.com/watch?v=" + props.videoIdTxt,
            reference: "",
            tag_keywords: props.keywordsTxt,
            author_name: props.authorTxt,
            cat_id: this.state.tempData.the_catId
        };


            this.props.adminUpdateBayaan_act(newBayaanObj)
                .then(() => {
                    this.props.adminFetchArticlesByCat_act(this.props.associatedMainCatId)
                        .then(() => {
                            this.props.toggleViewFunction();        // comming from Parent Class (bayaansPage)
                        });
                });


    }


    fetchCategoryId(value) {
        // make API call to fetch / generate category ID for this post
        this.props.adminGetCatIdByName_act(value, this.state.tempData.the_bayaansMainCat_id);               // '1': refers to look up under 'Bayaans' parent category for the specified category name
    }

    // will always receive and triggers when there are 'new props' and not old/same props


    render() {    // rendering Edit form
        const {handleSubmit} = this.props;
        console.log('<NewBayanForm> (render_editForm) this.props:', this.props);
        return (
            <div className="adminForm">
                <form onSubmit={handleSubmit(this.doSubmit.bind(this))}>
                    <div className="col-sm-6">
                        <div className="row">
                            <div className="col-sm-5"><label>Title:</label></div>
                            <div className="col-sm-7"><Field name="titleTxt" component={MySimpleInput}
                                                             defaultValue={this.props.name} type="text"
                                                             placeholder="Enter Title"/></div>
                        </div>
                        <div className="row">
                            <div className="col-sm-5"><label>Slug:</label></div>
                            <div className="col-sm-7">{this.state.tempData.slug || this.props.slug} <input
                                type="hidden" name="slugTxt" value={this.state.tempData.slug}/></div>
                        </div>
                        <div className="row">
                            <div className="col-sm-5"><label>Select Category:</label></div>
                            <div className="col-sm-7"><Field name="catTxt" component={MyCustomSelect}
                                                             defaultValue={this.props.category_name} type="text"
                                                             placeholder="Select or Type a New"
                                                             selectableOptionsList={this.state.tempData.the_autoSuggestCatList}
                                                             onSelectionDone={ this.fetchCategoryId.bind(this) }/>
                                <input type="hidden" name="catIdTxt"
                                       value={this.state.tempData.the_catId || this.props.category_id}/>
                            </div>
                        </div>
                    </div>
                    <div className="col-sm-6">
                        <div className="row">
                            <div className="col-sm-5"><label>Youtube Video ID:</label></div>
                            <div className="col-sm-7"><Field name="videoIdTxt" component={MySimpleInput}
                                                             defaultValue={this.props.content} type="text"
                                                             placeholder="TsQs9aDKwrw"/></div>
                            <div className="col-sm-12 hint"><b>Hint: </b> https://www.youtube.com/watch?v=<span
                                className="highlight">TsQs9aDKwrw</span></div>
                        </div>
                        <div className="row">
                            <div className="col-sm-5"><label>Author/Speaker:</label></div>
                            <div className="col-sm-7"><Field name="authorTxt" component={MySimpleInput}
                                                             defaultValue={this.props.author} type="text"/></div>
                        </div>
                        <div className="row">
                            <div className="col-sm-5"><label>Tags/Keywords:</label></div>
                            <div className="col-sm-7"><Field name="keywordsTxt" component={MySimpleInput}
                                                             defaultValue={this.props.tag_keywords} type="text"/>
                            </div>
                        </div>
                    </div>
                    <div className="row">
                        <div className={this.state.globalMessage.className}>{this.state.globalMessage.message}</div>
                    </div>
                    <div className="buttonControls">
                        <a className="cancelBtn" onClick={this.props.toggleViewFunction}>Cancel</a>
                        <button className={this.state.submitButtonMeta.btnClass}
                                disabled={this.state.submitButtonMeta.disabled}>
                            {this.state.submitButtonMeta.btnTitle}</button>
                    </div>
                </form>
            </div>
        );
    }


}

function validate(values) { // Validate function being called on Blur
    const errors = {};
    if (!values.titleTxt)
        errors.titleTxt = "Enter Title";
    if (!values.catTxt)
        errors.catTxt = "Select/Enter a Category";
    if (!values.videoIdTxt)
        errors.videoIdTxt = "Enter youtube video ID (follow the provided hint)";
    if (!values.keywordsTxt)
        errors.keywordsTxt = "Enter keywords (will help in search)";


    return errors;
}


// ReduxForm decorator 
const newBayanFormAdmin_reduxformObj = reduxForm({
    form: "newBayanFormAdmin",  // any unique name of our form
    validate                // totally equivelent to-->  validate: validate
});


function mapStateToProps({siteEssentials}, ownProps) {
    // 1st param is related to our Redux State, 2nd param relates to our own component props
    var initialValues = {
        titleTxt: ownProps.name,
        slugTxt: ownProps.slug,
        catTxt: ownProps.category_name,
        catIdTxt: ownProps.category_id,
        videoIdTxt: ownProps.content,
        authorTxt: ownProps.author,
        keywordsTxt: ownProps.tag_keywords
    };
    return ({siteEssentials}, initialValues);
};

function mapDispatchToProps(dispatch) {
    return bindActionCreators({
        adminFetchAutoSuggestCats_act,
        adminGetCatIdByName_act,
        adminAddNewBayaan_act,
        adminFetchArticlesByCat_act
    }, dispatch);
};


NewBayanForm = connect(mapStateToProps, mapDispatchToProps) (newBayanFormAdmin_reduxformObj(NewBayanForm));

export default NewBayanForm;

2 个答案:

答案 0 :(得分:2)

我发现这个教程非常简单且有用。

https://www.davidmeents.com/?p=38

答案 1 :(得分:0)

尝试initialValues获取更多details

export default NewBayanForm = reduxForm({ form: 'NewBayanForm', initialValues: {
  name: "abc",
  email: "abc@gmail.com",
  phoneNo: "1234567890"
} })(NewBayanForm)