如何使用React中的React / Redux表单编辑post值

时间:2016-05-30 20:29:32

标签: javascript reactjs redux react-redux redux-form

我正在使用react redux制作简单的博客。作为包我使用redux形式 我做了诸如post,get,delete之类的事件,但我无法进行编辑,因为我无法在编辑中获取值标题和正文。我尝试使用componentwillMount中的initialize来解决它,但是当我在ComponentWillMount中写 this.props.edit.title 时,无法读取未定义的属性'title' / p>

如何解决此问题,如何以编辑形式获取值

import React, { Component, PropTypes } from 'react';
import * as actions from '../../actions/index';
import { connect } from 'react-redux';
import {reduxForm} from 'redux-form';
import {initialize} from 'redux-form';

class EditPost extends Component {
    componentWillMount(){
    this.props.dispatch(initialize('edit', { title: this.props.edit.title },    ['title', 'body'])); 

    this.props.EditPost(this.props.params.id);
    }

handleFormSubmit(formProps){
this.props.addPost(formProps);
this.context.router.push('/posts');
}
    render(){
      const {handleSubmit,fields:{title,body}} = this.props;
        if(!this.props.edit){
            return <div>Loading...</div>;
        }
        return (
            <div>
          <div className="row">
          <div className="col-md-12">
                <form onSubmit={handleSubmit(this.handleFormSubmit.bind(this))}>
                <fieldset className="form-group">
                  <label>Title:</label>
                  <input {...title} className="form-control" />
                  {title.touched && title.error && <div className="text-danger">{title.error}</div>}
                  </fieldset>
                <fieldset className="form-group">
                  <label>Body:</label>
                  <textarea {...body} className="form-control" ></textarea>
                  {body.touched && body.error && <div className="text-danger">{body.error}</div>}
                </fieldset>
                 <button className="btn btn-success">Add</button>
                </form>
          </div>
          </div>
            </div>
               );
    }

    }

function mapStateToProps(state) {
    return {
        edit:state.posts.edit
    }
}
export default reduxForm({
form:'edit',
fields:['title','body'],},mapStateToProps,actions)(EditPost);

1 个答案:

答案 0 :(得分:2)

我用以下方式解决了问题。我可以使用 initialValues获取帖子值:state.posts.edit

function mapStateToProps(state) {
    return {
        edit:state.posts.edit,
        initialValues: state.posts.edit
    }
}