React-尽管具有默认值,但复选框值未定义

时间:2019-01-31 20:46:11

标签: javascript reactjs

我有一个问题,就是如果未触摸输入框,则会导致第一个复选框之后选中的所有复选框的sizemaxArrayElements都不确定。如果未触摸,它们都将默认设置为1

因此,在沙箱中,选择一个数据模式,选择器字段,选中一个框,仅选择lengthType,然后单击“提交”。该对象将返回(在控制台中),其默认值为sizearrayElements为1。

现在,如果我选中另一个框,只需选择lengthType,然后单击Submit,则sizearrayElements的值如果未被触摸,将返回未定义的状态。它们应该默认为1。我确实将placeholder的值设置为1,因此可能会引起误解。具体来说,输入value上的value={this.state.size[lastCheckedFieldName] || 1}道具通过将默认值设置为1(如果未更改)来处理此问题。但是由于某种原因,这不会发生

sandbox正在重现该问题。

import React from "react";
import ReactDOM from "react-dom";
import { Checkbox, CheckboxGroup } from "react-checkbox-group";
import axios from "axios";

import "./styles.css";

const schemas = [{ name: "Phone Data", id: "1" }];

const data = {
  data: {
    id: "2147483601",
    name: "Phone Data",
    fields: [
      {
        name: "Callee #"
      },
      {
        name: "Caller #"
      },
      {
        name: "Duration"
      }
    ]
  }
};

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      schemas: [],
      fields: [],
      size: {},
      lengthType: {},
      maxArrayElements: {},
      fieldNames: [],
      submitDisabled: true
    };

    this.onDataSchemaChange = this.onDataSchemaChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleCancel = this.handleCancel.bind(this);
  }

  componentDidMount() {
    axios({
      method: "get",
      url: `/list/of/schemas`
    })
      .then(response => {
        console.log(response);
        this.setState({ schemas: schemas });
      })
      .catch(error => console.log(error.response));
  }

  onDataSchemaChange = event => {
    const schema = this.state.schemas.find(
      schema => schema.name === event.target.value
    );
    if (schema) {
      axios({
        method: "get",
        url: ``
      })
        .then(response => {
          console.log(response);
          this.setState({
            fields: data.data.fields,
            selectedId: data.data.id
          });
          console.log(this.state.selectedId);
          console.log(this.state.fields);
        })
        .catch(error => console.log(error.response));
    }
  };

  onSizeChange = e => {
    e.persist();
    const { fieldNames } = this.state;
    const lastCheckedFieldName = fieldNames[fieldNames.length - 1];
    this.setState(
      prevState => {
        return {
          size: {
            ...prevState.size,
            [lastCheckedFieldName]: e.target.value
          }
        };
      },
      () => {
        console.log(this.state.size);
      }
    );
    console.log([e.target.name]);
  };

  onChangeMaxArrayElements = e => {
    e.persist();
    const { fieldNames } = this.state;
    const lastCheckedFieldName = fieldNames[fieldNames.length - 1];
    this.setState(
      prevState => {
        return {
          maxArrayElements: {
            ...prevState.maxArrayElements,
            [lastCheckedFieldName]: e.target.value
          }
        };
      },
      () => {
        console.log(this.state.maxArrayElements);
      }
    );
    console.log([e.target.name]);
  };

  handleSelectorFieldChange = event => {
    this.setState({ selectorField: event.target.value });
  };

  handleCancel = event => {
    event.target.reset();
  };

  fieldNamesChanged = newFieldNames => {
    this.setState({
      submitDisabled: !newFieldNames.length,
      fieldNames: newFieldNames,
      size: {
        [newFieldNames]: 1,
        ...this.state.size
      },
      maxArrayElements: {
        [newFieldNames]: 1,
        ...this.state.maxArrayElements
      }
    });
    console.log(this.state.size);
    console.log(this.state.maxArrayElements);
  };

  updateSelectorField = e => {
    this.setState({ selectorField: e.target.value });
  };

  updateLengthType = e => {
    e.persist();
    const { fieldNames } = this.state;
    const lastCheckedFieldName = fieldNames[fieldNames.length - 1];
    console.log("e", e);
    this.setState(prevState => {
      const lengthType = { ...prevState.lengthType };
      lengthType[lastCheckedFieldName] = e.target.value;
      return {
        lengthType
      };
    });
  };

  handleSubmit = event => {
    event.preventDefault();
    const fields = this.state.fieldNames.map(fieldName => ({
      name: fieldName,
      lengthType: this.state.lengthType[fieldName],
      size: this.state.size[fieldName],
      maxArrayElements: this.state.maxArrayElements[fieldName]
    }));
    console.log(fields);
  };

  render() {
    const { schemas, fields, fieldNames, selectorField } = this.state;
    const lastCheckedFieldName = fieldNames[fieldNames.length - 1];

    return (
      <div>
        <form onSubmit={this.handleSubmit}>
          <fieldset>
            <legend>
              <h2>QuerySchema Information</h2>
            </legend>
            <div className="info-boxes">
              <div>
                <label> Pick the dataschema to describe your data file:</label>{" "}
                <select
                  name="schemaName"
                  value={this.state.value}
                  onChange={this.onDataSchemaChange}
                >
                  <option value="">Choose Dataschema ...</option>
                  {schemas &&
                    schemas.length > 0 &&
                    schemas.map(schema => {
                      return <option value={schema.name}>{schema.name}</option>;
                    })}
                </select>
              </div>
            </div>
          </fieldset>
          <fieldset>
            <legend>
              <h2> DataSchema Fields </h2>
            </legend>
            <div className="selectorField-div">
              <div>
                <label>Selector Field:</label>{" "}
                <select
                  value={this.state.selectorField}
                  onChange={this.updateSelectorField}
                  required
                >
                  <option value="">Pick Selector Field...</option>
                  {fields &&
                    fields.map(field => {
                      return <option value={field.name}>{field.name}</option>;
                    })}
                </select>
              </div>
              {selectorField && (
                <fieldset>
                  <div>
                    <legend>Choose field names</legend>
                    <CheckboxGroup
                      checkboxDepth={5}
                      name="fieldNames"
                      value={this.state.fieldNames}
                      onChange={this.fieldNamesChanged}
                      required
                    >
                      {fields &&
                        fields.map(field => {
                          return (
                            <li>
                              <Checkbox value={field.name} />
                              {field.name}
                            </li>
                          );
                        })}
                    </CheckboxGroup>
                  </div>{" "}
                </fieldset>
              )}
            </div>
            <div className="input-boxes">
              {lastCheckedFieldName && (
                <div>
                  <label>Length Type:</label>
                  <select
                    value={this.state.lengthType[lastCheckedFieldName] || ""}
                    onChange={this.updateLengthType}
                    required
                  >
                    <option value="">Select Length Type...</option>
                    <option value="fixed">Fixed</option>
                    <option value="variable">Variable</option>
                  </select>
                </div>
              )}
              {lastCheckedFieldName && (
                <div>
                  <label>Size:</label>
                  <input
                    value={this.state.size[lastCheckedFieldName] || 1}
                    onChange={this.onSizeChange}
                    type="number"
                    name="size"
                    min="1"
                    placeholder="1"
                    required
                  />
                </div>
              )}
              {lastCheckedFieldName && (
                <div>
                  <label>MaxArray Elements:</label>
                  <input
                    value={
                      this.state.maxArrayElements[lastCheckedFieldName] || 1
                    }
                    onChange={this.onChangeMaxArrayElements}
                    type="number"
                    name="maxArrayElements"
                    placeholder="1"
                    min="1"
                    max="100"
                    required
                  />
                </div>
              )}
            </div>
          </fieldset>

          <div className="btn-group">
            <span className="input-group-btn">
              <button
                className="btnSubmit"
                handleSubmit={this.handleSubmit}
                type="submit"
                disabled={this.state.submitDisabled}
              >
                Submit{" "}
              </button>
              <button
                className="btnReset"
                handleCancel={this.handleCancel}
                type="reset"
                onClick={() => {
                  alert("Clearing current field values.");
                }}
              >
                Reset
              </button>
            </span>
          </div>
        </form>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

1 个答案:

答案 0 :(得分:1)

我已经在state函数的末尾检查了handleSubmit的输出,它看起来像这样:

lengthType: {
  "Callee #": "fixed",
  "Caller #": "variable"
},
maxArrayElements: {
  "Callee #,Caller #": 1,
  "Callee #": 1
}
fieldNames: [
 0: "Callee #"
 1: "Caller #"
]

这里的问题是lengthTypemaxArrayElements中的键都被错误命名。您正在设置onChange中的这些键值对CheckboxGroup。问题的根源在于传递给fieldNamesChanged函数的参数。 CheckboxGroup总是通过Array选中的复选框,而不仅仅是新的复选框。我建议仅从newFieldNames中获取最后一条记录,并将其添加到状态中。

fieldNamesChanged = newFieldNames => {
    this.setState({
      submitDisabled: !newFieldNames.length,
      fieldNames: newFieldNames,
      size: {
        [newFieldNames[newFieldNames.length - 1]]: 1,
        ...this.state.size
      },
      maxArrayElements: {
        [newFieldNames[newFieldNames.length - 1]]: 1,
        ...this.state.maxArrayElements
      }
    });
  };