简体   繁体   English

如何将选择下拉列表的数据从Redux形式传递到Redux中的后端api

[英]How to pass select dropdown's data from redux-form to backend api in redux

I have a redux form where I have 2 input fields and one select drop-down. 我有一个redux表单,其中有2个输入字段和一个select下拉列表。 I wan to store the values of the inputs to a backend api. 我想将输入的值存储到后端api。 I am able to get the values from the inputs and pass it to the server, but for some reason I am not able to correctly get the select drop-down value and pass it to the back-end server. 我能够从输入中获取值并将其传递到服务器,但是由于某些原因,我无法正确获取选择下拉值并将其传递到后端服务器。 I know I am doing some silly mistake with the state, but I am not able to figure out what is that.My file is as shown below: 我知道我在状态上犯了一些愚蠢的错误,但是我无法弄清楚那是什么。我的文件如下所示:

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

class CreatePost extends Component {
  constructor() {
    super();
    this.state = {
      selectValue : 'react'
  };
  this.handleChange = this.handleChange.bind(this);
  this.renderCategory = this.renderCategory.bind(this);
}

  renderField(field) {
      return(
        <div className="title-design">
            <label className="label-design"> {field.label} </label>
            <input
              type="text"
              className="title-input"
              {...field.input}
            />
            <div className="text-help  has-danger">
              {field.meta.touched ? field.meta.error : ''}
            </div>
      </div>
      );
  }

  handleChange(e) {
    this.setState({selectValue: e.target.value});
    console.log(this.state.selectValue);
  }

  renderCategory(field) {
    return(
      <div className="title-design">
        <label className="label-design">{field.label} </label>

        <select
          name="categories"
          className="title-input"
          value={this.state.selectValue}
          onChange={this.handleChange}  >
              <option value="react">React</option>
              <option value="redux">Redux</option>
              <option value="udacity">Udacity</option>
        </select>
        {this.state.selectValue}
      </div>
    );
  }

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

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

      return (
        <form onSubmit={handleSubmit(this.onSubmit.bind(this))}>
          <Field
            label="Title for Post"
            name="title"
            component={this.renderField}
          />

          <Field
            label="Post Content"
            name="body"
            component={this.renderField}
          />

          <Field
            label="Category"
            name="category"
            component={this.renderCategory}
          />

          <button type="submit" className="btn btn-primary">Submit</button>
          <Link  to="/">
            <button className="cancel-button">Cancel</button>
          </Link>
        </form>
      );
    }
}

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

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

  if (!values.body) {
    errors.body = "Enter some content";
    }

  return errors;
}

export default reduxForm({
  validate : validate,          //validate
  form : 'CreatePostForm'
})(
  connect(null,{ createPosts })(CreatePost)
);

NOTE: Also,I want to generate a unique id for each of the records that is passed to the server so that I can refer to them when I want to retrieve data and display it.Can anyone please guide me how to proceed with both the issues? 注意:另外,我想为传递到服务器的每条记录生成唯一的ID,以便在我要检索数据并显示它时可以引用它们。任何人都可以指导我如何同时处理这两个记录。问题?

setState is not synchronous, it has a callback so you should have something like: setState不是同步的,它具有回调,因此您应该具有以下内容:

handleChange(e) {
    this.setState({selectValue: e.target.value}, () => {
       console.log(this.state.selectValue);
   });
}

To set the value of the field, you can use change whose signature is: 要设置字段的值,可以使用change它的签名是:

change(field:String, value:any)

So your handler will just become: 因此,您的处理程序将变为:

handleChange(e) {
    const value = e.target.value;
    this.props.change("categories", value);
    this.setState({ "selectValue": value }, () => {
      console.log(value);
    });    
}

and in your renderCategory you can remove the value attribute: 在您的renderCategory您可以删除value属性:

... 
<select
    name="categories"
    className="title-input"
    onChange={this.handleChange} >
...

To set some random id for every submission, you can find lots of libraries to generate a random one; 要为每次提交设置一些随机ID,您可以找到很多库来生成一个随机ID。 to assign to the record, use again change method and field "id" will be sent to the server: 要分配给记录,请再次使用change方法,并将字段“ id”发送到服务器:

this.props.change('id', <random generated Id>)

See this sandbox a rough implementation 看到此沙箱的大致实现

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM