反应-在后请求中发送存储的状态值-格式错误的数据

时间:2018-10-18 19:56:24

标签: javascript reactjs axios

我有一组复选框,并且选中每个复选框时,每个复选框都可以具有自己的lengthTypesize值,这些值存储为状态。 我也做了一个沙箱:https://codesandbox.io/s/j29yp2j905

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      fields: ["action", "callee", "caller", "duration", "message"],
      fieldNames: [],
      size: {},
      lengthType: {},
      maxArrayElements: {}
    };

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  fieldNamesChanged = newFieldNames => {
    console.log("newFiledNames", newFieldNames);
    this.setState({ fieldNames: newFieldNames });
  };

  onChange = 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([e.target.name]);
  };

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

  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([e.target.name]);
  };

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

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

    axios({
      method: "post",
      url: `/some/url`,
      headers: {
        Accept: " ",
        "Content-Type": "application/json"
      },
      data: JSON.stringify({
        name: this.state.qsName,
        selectorField: this.state.selectorField,
        fields: fields
      })
    })
      .then(response => {
        console.log(response);
        this.setState({ querySchemaId: response.data.data.id });
      })
      .catch(error => console.log(error.response));
  };

  render() {
    const { fields, fieldNames } = this.state;

    const lastCheckedFieldName = fieldNames[fieldNames.length - 1];

    return (
      <div className="App">
        <h1>Checkbox Group</h1>

        <div>
          <form onSubmit={this.handleSubmit}>
            <fieldset>
              <legend>Choose field names</legend>
              <br />
              <CheckboxGroup
                checkboxDepth={5}
                name="fieldNames"
                value={this.state.fieldNames}
                onChange={this.fieldNamesChanged}
              >
                {fields &&
                  fields.map(field => {
                    return (
                      <label>
                        <Checkbox value={field} />
                        {field}
                      </label>
                    );
                  })}
                <br />
              </CheckboxGroup>
              <br />
              {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>
              )}
              <br />
              {lastCheckedFieldName && (
                <div>
                  <label>Size:</label>
                  <input
                    value={this.state.size[lastCheckedFieldName] || 1}
                    onChange={this.onChange}
                    type="number"
                    name="size"
                    placeholder="1"
                    min="0"
                    required
                  />
                </div>
              )}
              <br />

              {lastCheckedFieldName && (
                <div>
                  <label>MaxArray Elements:</label>
                  <input
                    value={
                      this.state.maxArrayElements[lastCheckedFieldName] || 1
                    }
                    onChange={this.onChangeMaxArrayElements}
                    type="number"
                    name="maxArrayElements"
                    placeholder="1"
                    min="0"
                    max="100"
                    required
                  />
                </div>
              )}
            </fieldset>

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

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

当我提交此表单数据时,正在发送的状态值发生了奇怪的事情。

由于一些更改,我发送的数据已变得格式错误:

"data": 
    "{\"name\":\"QS7\",
    \"selectorField\":\"callee\",
    \"fields\":
        [{\"name\":\"action\",
        \"lengthType\":{\"action\":\"fixed\"},
        \"size\":{\"action\":\"3\"},
        \"maxArrayElements\":{\"action\":\"4\"}
        }]}"

应该是这样

"data": 
    "{\"name\":\"QS7\",
    \"selectorField\":\"callee\",
    \"fields\":
        [{\"name\":\"action\",
        \"lengthType\":\"fixed\",
        \"size\":\"3\"},
        \"maxArrayElements\":\"4\"}
        }]}"
由于某种原因,

field.name被作为数组中的第一个值添加到每个字段元素。

1 个答案:

答案 0 :(得分:1)

您将arrayOrObjWithData = ['1'] || {id: 1} <h1 *ngxIfNotEmpty="arrayOrObjWithData"> You will see it </h1> or // store the result of async pipe in variable <h1 *ngxIfNotEmpty="arrayOrObjWithData$ | async as obj"> {{obj.id}} </h1> or noData = [] || {} <h1 *ngxIfHasItems="noData"> You will NOT see it </h1> lengthTypesizemaxArrayElements的形式存储在{ fieldName: value }中。因此,您可能忘记了在state方法的映射回调中为当前fieldName选择它们中的每一个。因此handleSubmit基本上应该这样映射:

fields