从mapStateToProps重新形成初始值

时间:2017-06-02 23:55:28

标签: javascript reactjs redux react-redux

如何将notesFromStore提供的redux带到我的NoteEdit组件中:

function mapStateToProps(state) {
  return { notesFromStore: state.notes };
}

当组件安装时,将它们设为<Field name="title"><Field name="content">的初始值?

class NoteEdit extends Component {

  onSumbit(values) {
    this.props.createNote(values, () => {
      this.props.history.push('/');
    });
  }

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

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

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

    return (
      <form onSubmit={handleSubmit(this.onSumbit.bind(this))}>
        <Field
          name="title"
          labelToShow="Note title"
          component={this.renderField}
        />
        <Field
          name="content"
          labelToShow="Note content"
          component={this.renderField}
        />
        <button type="submit" className="btn btn-primary">Submit</button>
        <Link to="/" className="btn btn-danger">Cancel</Link>
      </form>
    );
  }
}

export default reduxForm({
  validate: validate,
  form: 'NoteNewFormUnique',
})(connect(null, { createNote })(NoteEdit));

屏幕显示从redux mapStateToProps

传递的数据结构

修改

感谢: @Ashish Choudhary 它有效!我将留下我的代码给未来有类似问题的人。也许它会有所帮助。

import React, { Component } from 'react';
import { Field, reduxForm } from 'redux-form';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';

class NoteEdit extends Component {

  componentWillReceiveProps(nextProps) {
    const { change } = this.props
    const values = nextProps.initialValues;
    if (values !== null) {
      change('title', values.title);
      change('content', values.content);
    }
  }

  onSumbit(values) {
    this.props.prepareToEdit(values, () => {
      this.props.history.push('/');
    });
  }

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

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

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

    return (
      <form onSubmit={handleSubmit(this.onSumbit.bind(this))}>
        <Field
          name="title"
          labelToShow="Note title"
          component={this.renderField}
        />
        <Field
          name="content"
          labelToShow="Note content"
          component={this.renderField}
        />
        <button type="submit" className="btn btn-primary">Submit</button>
        <Link to="/" className="btn btn-danger">Cancel</Link>
      </form>
    );
  }
}

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


function validate(values) {
  const errors = {};
  if (!values.title || values.title.length < 2) {
    errors.title = 'Enter note title that is at least 2 characters long!';
  }
  if (!values.content || values.content.length < 3) {
    errors.content = 'Enter note content that is at least 3 characters long!';
  }
  // If errors is empty, the form is fine to submit
  // If errors has any properties, it is invalid
  return errors;
}

export default reduxForm({
  validate: validate,
  form: 'NoteNewFormUnique',
})(connect(mapStateToProps, null)(NoteEdit));

2 个答案:

答案 0 :(得分:2)

准确地说,change函数是绑定redux-form中数据的最佳方法,因为它可以很容易地在类中的任何地方使用...因此不需要为此设置初始状态形式...

class NoteEdit extends Component {

  componentWillReceiveProps(nextProps) {
    const { change } = this.props
    const values = nextProps.initialValues.5931aa20b94dc80011c729d6
    change('title', values.title)
  }

  render() {
    const { handleSubmit } = this.props
    return (
      <form onSubmit={handleSubmit(this.onSumbit.bind(this))}>
        <Field
          name="title"
          labelToShow="Note title"
          component={this.renderField}
        />
      </form>
    )
  }
}

答案 1 :(得分:0)

对于更通用的方法,我建议使用以下componentWillReceiveProps函数。您无需指定要更改的字段,因为它们都是从nextProps.initialValues读取的。

componentWillReceiveProps(nextProps) {
    const { change, initialValues } = this.props
    const values = nextProps.initialValues;

    if(initialValues !== values){
        for (var key in values) {
            if (values.hasOwnProperty(key)) {
                change(key,values[key]);
            }
        }
    }
}