【问题标题】:React Axios Input Undefined反应 Axios 输入未定义
【发布时间】:2020-05-31 19:10:34
【问题描述】:

我必须使用 Axios 将 {input} 数据发布到 http://localhost:4000/prediction。但 {input} 变为未定义。

我使用的是 const 而不是 class Main extends 组件。 onChange,它设置表单数据。

const Main = ({ value, suggestions, auth: { user } }) => {

  const [formData, setFormData] = useState("");

  const [messages, setMessages] = useState([]);

  const { input } = formData;

  const onChange = e => setFormData(e.target.value);

  const onSubmit = event => {
    event.preventDefault();
    setMessages(prevMsgs => [...prevMsgs, formData]);

    console.log({ input });

Axios 帖子。

    axios
      .post(
        `http://localhost:4000/prediction`,
        { input },
        { crossdomain: true }
      )
      .then(res => {
        console.log(res.data);
        //setMessages(prevMsgs => [...prevMsgs, formData]);
      })
      .catch(error => {
        console.log(error.message);
      });
  };

使用 onSubmit、onChange 返回(表单)。

  return (
    <div className="true">
      <br />
      <form noValidate onSubmit={e => onSubmit(e)}>
        <div className="input-group mb-3">
           <input
                name="input"
                type="text"
                className="form-control"
                placeholder="Type text"
                onChange={e => onChange(e)}
              />
            )}
          <div className="input-group-append">
            <button className="btn btn-outline-secondary">Send</button>
          </div>
        </div>
      </form>
    </div>
  );
};

【问题讨论】:

  • formData 是一个字符串,正如我所见,它没有名为 input 的属性,您尝试解构它。

标签: javascript node.js reactjs axios


【解决方案1】:

正如我在评论部分提到的,formData 是一个字符串,因为我看到它没有一个名为 input 的属性,你试图解构它,这就是为什么它总是 undefined

如果您确实需要 axios 的格式,那么您可以尝试先将 formData 的结构更改为 useState,如下所示:

const [formData, setFormData] = useState({input: null});

那么也许你可以尝试更新为:

const onChange = e => setFormData({input: e.target.value});

希望对你有帮助!

【讨论】:

  • 谢谢,还有一件事。我们真的不能输入“表单数据”吗?如何设置 {input} 以形成数据? const data = new FormData(); data.set("input", { input }); 效果不佳。
猜你喜欢
  • 2021-08-24
  • 2021-05-26
  • 1970-01-01
  • 2021-04-28
  • 2021-11-02
  • 1970-01-01
  • 2020-07-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多