2

我正在用 react redux 制作简单的博客。作为包,我使用的是 redux 表单,我制作了诸如发布、获取、删除之类的事件,但我无法编辑表单,因为我无法在编辑中获取值标题和正文。我尝试通过在 componentwillMount 中进行初始化来解决它,但是 当我在 ComponentWillMount 中编写this.props.edit.title时,无法读取未定义的属性“标题”会出错

我该如何解决这个问题,如何在编辑表单中获取值

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);
4

1 回答 1

2

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

function mapStateToProps(state) {
    return {
        edit:state.posts.edit,
        initialValues: state.posts.edit
    }
}
于 2016-05-31T16:59:54.970 回答