首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在带有钩子的函数处理程序中使用useRef

在带有钩子的函数处理程序中使用useRef
EN

Stack Overflow用户
提问于 2021-04-29 07:32:22
回答 1查看 63关注 0票数 0

我试图提交一个发送http请求onSubmit的表单,但是当设置值的状态时,我会变得没有定义。我不知道为什么在单击和设置set .()函数时没有传递这些值。

下面是该组件的代码。在第一次提交操作时,我会得到一个错误,因为"surveyUserAnswers“是未定义的,但是在下一个提交中它可以工作。不知道为什么?有人能告诉我。

我对打字和反应很陌生,所以请原谅我的代码!谢谢

代码语言:javascript
复制
import React, { useRef, useState } from "react";

import Loader from "../UI/loader/loader";

import axios from "axios";
import "./surveybox.css";

interface surveryAnswer {
  id: number;
  answers: string[];
}

const SurveyBox: React.FC = () => {
  const [surveyUserAnswers, setSurveyUserAnswers] = useState<surveryAnswer>();
  const [loading, setLoading] = useState(false);
  const programmingQRef = useRef<HTMLSelectElement>(null);
  const skillsQRef = useRef<HTMLSelectElement>(null);
  const stateManagementQRef = useRef<HTMLSelectElement>(null);
  const programmerTypeQRef = useRef<HTMLSelectElement>(null);

  const onSubmitSurvey = (e: React.FormEvent): void => {
    e.preventDefault();
    setLoading((prevLoading) => !prevLoading);
    setSurveyUserAnswers({
      id: Math.random(),
      answers: [
        programmerTypeQRef.current!.value,
        skillsQRef.current!.value,
        stateManagementQRef.current!.value,
        programmerTypeQRef.current!.value,
      ],
    });

    axios
      .post(`${DB_URL}/users-answers.json`, surveyUserAnswers)
      .then((res) => {
        setLoading((prevLoading) => !prevLoading);
      })
      .catch((error) => {
        console.log(error);
        setLoading((prevLoading) => !prevLoading);
      });
  };

  return (
    <div className="surveybox-container">
      {loading ? (
        <div className={"loader-holder"}>
          <Loader />
        </div>
      ) : (
        <React.Fragment>
          <h2>Quick survey!</h2>
          <form action="submit" onSubmit={onSubmitSurvey}>
            <label>favorite programming framework?</label>
            <select ref={programmingQRef} name="programming">
              <option value="React">React</option>
              <option value="Vue">Vue</option>
              <option value="Angular">Angular</option>
              <option value="None of the above">None of the above</option>
            </select>
            <br></br>
            <label>what a junior developer should have?</label>
            <select ref={skillsQRef} name="skills">
              <option value="Eagerness to lear">Eagerness to learn</option>
              <option value="CS Degree">CS Degree</option>
              <option value="Commercial experience">
                Commercial experience
              </option>
              <option value="Portfolio">Portfolio</option>
            </select>
            <br></br>
            <label>Redux or Context Api?</label>
            <select ref={stateManagementQRef} name="state-management">
              <option value="Redux">Redux</option>
              <option value="Context Api">Context Api</option>
            </select>
            <br></br>
            <label>Backend, Frontend, Mobile?</label>
            <select ref={programmerTypeQRef} name="profession">
              <option value="Back-end">back-end</option>
              <option value="Front-end">front-end</option>
              <option value="mobile">mobile</option>
            </select>
            <br></br>
            <button type="submit">submit</button>
          </form>
        </React.Fragment>
      )}
    </div>
  );
};

export default SurveyBox;
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-04-29 07:37:52

设置状态是一个异步操作,更新后的状态只有在下一个呈现时才可用。

在您的示例中,默认状态是undefined,这就是您在第一次提交时发送的内容。状态现在更新,当您再次提交时,您发送先前的答复,等等.

要解决这个问题,请准备一个const (newAnswer),并将其设置为状态,并在api调用中使用它。

注意事项:在您的例子中,您根本没有使用surveyUserAnswers,所以您可以完全删除这个状态。

代码语言:javascript
复制
const onSubmitSurvey = (e: React.FormEvent): void => {
  e.preventDefault();
  setLoading((prevLoading) => !prevLoading);

  const newAnswer = {
    id: Math.random(),
    answers: [
      programmerTypeQRef.current!.value,
      skillsQRef.current!.value,
      stateManagementQRef.current!.value,
      programmerTypeQRef.current!.value,
    ],
  }

  setSurveyUserAnswers(newAnswer);

  axios
    .post(`${DB_URL}/users-answers.json`, newAnswer)
    .then((res) => {
      setLoading((prevLoading) => !prevLoading);
    })
    .catch((error) => {
      console.log(error);
      setLoading((prevLoading) => !prevLoading);
    });
};
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67312917

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档