【问题标题】:Nested Objects Axios Post嵌套对象 Axios Post
【发布时间】:2021-07-27 09:47:19
【问题描述】:

我正在尝试将一个包含多个选项的数组发布到一个名为 options 的数组中,该数组来自一个带有文本框的表单。但是,不是在参数 options 下有多个选项,而是每个选项都被另一个选项覆盖。

挂钩

  const [description, setDescription] = useState("");
  const [text, setText] = useState("");
  const [type, setType] = useState("");
  const [options, setOptions] = useState([]);

提交函数

    e.preventDefault();
    axios({
      method: "post",
      url: "http://localhost:8080/new/",
      data: {
      
        title: title,
        description: description,
      
      questions:{
         text: text,
        type: type,
        options: options,
      } 
      
      },
      config: { headers: { "Content-Type": "application/json" } },
    })
      .then(function () {
        alert("Successfully submitted application.");
      })
      .catch(function (error) {
        alert("Failed to submit application.");
        console.log(error);
      });
  }

表单中的选项部分

 <input
            required
            type="options"
            id="options"
            name="options"
            value={options}
            onChange={(e) => setOptions(e.target.value)}
            placeholder="ex. A).Blue"
          />
          <br />
          B:&nbsp;&nbsp;
          <input
            required
            type="options"
            id="options"
            name="options"
            value={options}
            onChange={(e) => setOptions(e.target.value)}
            placeholder="ex. B).Red"
          />
          <br />

提交按钮

          variant="primary"
          onClick={(e) => {
            SubmitQuiz(e);
          }}
          type="submit"
        >
          Submit Quiz
        </button>

输出

title   "I"
description "need"
questions   
text    "some"
type    "Select One"
options "help"

想要的输出

【问题讨论】:

  • 什么会被覆盖?输出从哪里来?

标签: javascript express axios


【解决方案1】:

使用map创建多个输入,然后将输入名称设置为:

i = 0;

name=`options.${i}`

使用此i 变量的增量。

在您的示例中使用如下:

<input
    required
    type="options"
    id="options"
    name="options.0"
    value={options}
    onChange={(e) => setOptions(e.target.value)}
    placeholder="ex. A).Blue"
 />
 <br />
 B:&nbsp;&nbsp;
 <input
     required
     type="options"
     id="options"
     name="options.1"
     value={options}
     onChange={(e) => setOptions(e.target.value)}
     placeholder="ex. B).Red"
 />
 <br />

【讨论】:

    猜你喜欢
    • 2021-03-12
    • 2017-06-23
    • 2020-09-06
    • 2021-11-16
    • 2021-01-16
    • 1970-01-01
    • 2020-06-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多