簡體   English   中英

使用 console.log 檢查 React useState() 不能正常工作

[英]Check React useState() with console.log doesn't work properly

我正在嘗試使用 react useState 從 2 個文本框中獲取數據。 但是當我檢查console.log時,它會將文本字母一個一個地作為一個數組。

創建.js

import React, {useState} from 'react'
import { Form, Button, FormGroup, FormControl, ControlLabel } from "react-bootstrap";

export default function Create() {
    const[firstName, setFirstName] = useState('');
    const[lastName, setLasttName] = useState('');

    console.log(firstName);
    console.log(lastName);
  return (
      <div>
    <div>create</div>
    <div>

    <Form>
        <Form.Group className="mb-3" >
        <Form.Label>First Name</Form.Label>
        <Form.Control type="text" name='fName'  
        onChange={(e)=> setFirstName(e.target.value)} 
        placeholder="Enter first name" />
        </Form.Group>

        <Form.Group className="mb-3">
        <Form.Label>Last Name</Form.Label>
        <Form.Control type="text" name='lName'  
        onChange={(e)=> setLasttName(e.target.value)} 
        placeholder="Enter last name" />
        </Form.Group>

        
        
        <Button variant="primary" type="submit">
        Submit
        </Button>
</Form>
    </div>
    </div>
  )
}

應用程序.js

import './App.css';
    
import Create from './Components/create';


function App() {
  return (
    <div className="App">
        <h2>Hello</h2>
        <Create/>
        
    </div>
  );
}

export default App;

這就是控制台的樣子。

控制台應如下圖所示

輸出應該如何

每次輸入更改時都會觸發onChange函數。 如果您希望它只觸發一次,當您完成輸入時,您可以使用onBlur這將僅在輸入字段變得模糊時分配值。

這是一個沙盒供您使用。 確保檢查控制台以查看 firstName 何時更新https://codesandbox.io/s/pedantic-tharp-rfnxqg?file=/src/App.js

我強烈建議您查看React Hook Forms

import React, {useState} from 'react'
import { Form, Button, FormGroup, FormControl, ControlLabel } from "react-bootstrap";

export default function Create() {
    const[firstName, setFirstName] = useState('');
    const[lastName, setLasttName] = useState('');

    const submitForm =(e)=>{
     console.log(firstName)
console.log(lastName)
e.preventDefault()
}
  return (
      <div>
    <div>create</div>
    <div>

    <Form onSubmit={(e)=>submitForm(e)}>
        <Form.Group className="mb-3" >
        <Form.Label>First Name</Form.Label>
        <Form.Control type="text" name='fName'  
        onChange={(e)=> setFirstName(e.target.value)} 
        placeholder="Enter first name" />
        </Form.Group>

        <Form.Group className="mb-3">
        <Form.Label>Last Name</Form.Label>
        <Form.Control type="text" name='lName'  
        onChange={(e)=> setLasttName(e.target.value)} 
        placeholder="Enter last name" />
        </Form.Group>

        
        
        <Button variant="primary" type="submit">
        Submit
        </Button>
</Form>
    </div>
    </div>
  )
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM