React 中的 OnSubmit

Posted

技术标签:

【中文标题】React 中的 OnSubmit【英文标题】:OnSubmit in React 【发布时间】:2022-01-05 20:28:51 【问题描述】:

不知道为什么 onSubmit 函数不能正常工作。

我有组件InputForm

import React,  useState, useRef, useEffect  from "react";
import Input from "../UI/Input";
import TextArea from "../UI/TextArea";
import Comments from "./Comments";
import classes from "./InputForm.module.css";
import Button from "../UI/Button";

const InputForm = (props) => 
  const [userInput, setUserInput] = useState( userName: "", userText: "" );
  const [comments, setComments] = useState([]);

  const nameInput = useRef();
  const commentText = useRef();

  const submitHandler = (event) => 
    event.preventDefault();
    const enteredName = nameInput.current.value;
    const enteredText = commentText.current.value;

    setUserInput( userName: enteredName, userText: enteredText );
    setComments((prev) => 
      return [...prev, userInput];
    );
  ;

  console.log(comments);

  return (
    <div>
      <form className=classes.inputForm onSubmit=submitHandler>
        <Input
          ref=nameInput
          label="Your Name"
          input=
            id: "name",
            type: "text",
            placeholder: "Hello, what's your name?",
          
        />
        <TextArea
          ref=commentText
          label="Comment Out"
          inputTextArea=
            name: "comment",
            id: "comment",
            cols: "30",
            rows: "4",
            placeholder:
              "So sweet image, isn't it ah..? Comment out, don't be shy...",
          
        />
        <Button buttonText="Leave comment" />
      </form>
      <Comments userData=comments />
    </div>
  );
;

export default InputForm;
**strong text**

我得到用户的名字和文本数据并将其发送到另一个组件cmets

import React from "react";
import  Fragment  from "react/cjs/react.production.min";
import classes from "./Comment.module.css";

const Comments = (props) => 
  const userData = props.userData;
  console.log(userData.length);
  const comments = userData.map((user) => 
    return (
      <div className=classes.comment>
        <h3>user.userName</h3>
        <p className=classes.commentText>user.userText</p>
      </div>
    );
  );

  return <Fragment>comments</Fragment>;
;

export default Comments;

问题是当我点击按钮提交时,我得到空数据,当我第二次点击时我得到用户的数据,为什么会这样?

图像上的结果。

【问题讨论】:

【参考方案1】:

这是因为您在 userInput 状态更新后立即更新了 cmets 状态。

状态更新只存在于下一次渲染中,因此您传递给 setComments 的用户输入仍然是您设置的初始值。

尝试使用 useEffect 更新 cmets 并删除 setUserInput 下的 setComments

useEffect(()=>
  setComments(prev=> [...prev, userInput)
,[userInput])

【讨论】:

以上是关于React 中的 OnSubmit的主要内容,如果未能解决你的问题,请参考以下文章

React 深入系列1:React 中的元素组件实例和节点

React开发(214):React中的Fragments

将 Relay 中的数据与 React Native 中的 react-navigation 一起使用时,未获取 Relay 中的数据

浅析react中的react-router和react-router-dom

深入理解react中的虚拟DOMdiff算法

深入理解react中的虚拟DOMdiff算法