简体   繁体   中英

OnSubmit in React

Can't figure out why onSubmit function work incorrectly.

I have component 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**

I get user's name and text data and send it to the other component comments :

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;

The problem is when i clicked on button to submit, i get empty data and when i click in second time i get user's data, why it happening?

Result on image. 在此处输入图像描述

It is because you update the comments state right after the userInput state update.

State updates only exists in the next rendering, so the userinput you pass to the setComments remains the initial value you set.

try using the useEffect to update the comments and remove the setComments under the setUserInput

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM