2017-06-29 16 views
0

reactx/reduxをredux-formで使用しています。何らかの理由で入力値が編集フォームに表示されません。React/redux入力値が表示されない

私はconsole.logを投稿し、そこにいることを示していますが、何らかの理由で動作していません。私は以下のコードを投稿します。

編集コンポーネントは:

import React , { Component } from 'react'; 
import * as actions from '../../actions/posts_actions'; 
import { reduxForm, Field } from 'redux-form'; 
import {connect} from 'react-redux'; 
import {Link} from 'react-router-dom'; 

class EditPost extends Component { 
    componentDidMount() { 
    const {id} = this.props.match.params; 
    this.props.getOnePost(id); 
    } 

    renderField(field) { 
    const { meta: {touched, error} } = field; 
    const className = `form-group ${touched && error ? 'has-danger' : ''}`; 

    return (
     <div className={className}> 
     <label><strong>{field.label}:</strong></label> 
     <input 
      className="form-control" 
      type={field.type} 
      value={field.value} 
      {...field.input} 
     /> 
     <div className="text-help"> 
      { touched ? error : ''} 
     </div> 
     </div> 
    ) 
    } 

    onSubmit(values) { 
    const {id} = this.props.match.params; 

    this.props.updatePost(values, id,() => { 
     this.props.history.push(`/posts/${id}`); 
    }); 
    } 

    render() { 
    const {handleSubmit} = this.props; 

    const {post} = this.props; 

    if(!post) { 
     return <div> Loading... </div>; 
    } 
    console.log(post); 

    return (
     <form onSubmit={handleSubmit(this.onSubmit.bind(this))}> 
     <Field 
      label="Title" 
      name="title" 
      type="text" 
      value={post.title} 
      component={this.renderField} 
     /> 
     <Field 
      label="Content" 
      name="content" 
      type="text" 
      value={post.content} 
      component={this.renderField} 
     /> 
     <button type="submit" className="btn btn-success">Submit</button> 
     <Link to={`/posts/${post._id}`} className="btn btn-danger">Cancel</Link> 
     </form> 
    ); 
    } 
} 

function validate(values) { 
    const errors = {}; 

    if(!values.title) { 
    errors.title = "Enter a title!"; 
    } 
    if(!values.content) { 
    errors.content = "Enter some content please!"; 
    } 

    return errors; 
} 

function mapStateToProps({ posts }, ownProps) { 
    return { post: posts[ownProps.match.params.id] }; 
} 

export default reduxForm({ 
    validate, 
    form: 'editform' 
})(connect(mapStateToProps, actions)(EditPost)); 

答えて

0

代わりに値を直接設定するので、initialValues小道具を渡す:

function mapStateToProps({ posts }, ownProps) { 
    const post = posts[ownProps.match.params.id] 
    return { 
    post, 
    initialValues: { 
     ...post 
    } 
    }; 
} 

はフォームでField sからvalue小道具を削除します。 Postオブジェクトのプロパティが、入力するフィールドの名前と同じであれば、オブジェクトスプレッドを使用できます。それらが異なる場合は、適切

initialValues: { 
    contentField: post.content 
} 

<Field name="contentField" /> 

初期値は、あなたがreduxFormエンハンサーを使用前を設定する必要があり、それらをマッピングする必要があります。また、モデルが更新された場合にフォームの値を更新する場合は、reduxFormの設定にenableReinitialize: trueを追加します。

関連する問題