簡體   English   中英

使用 React Javascript(Form-Onsubmit 和調用 API 無法正常工作)

[英]Using React Javascript (Form-Onsubmit & calling API not working properly)

閱讀下面的代碼時,我對邏輯有點困惑,盡管代碼可以正常工作,但並不完全符合我的期望。

如果有人可以澄清,我有 3 個疑問。

1-據我所知,useEffect 用於在渲染后調用 function,但在下面的代碼中,一旦表單被提交(onSubmit={credentialVerify}),它將調用 credentialVerify() function 認為我們需要如下,所以我不需要useEffect 在這里,但除非我使用 useEffect 語句,否則代碼仍然不會調用 API。

2-也不等我先輸入我的憑據,只要我 go 到登錄頁面,它就會獲取 API(使用 useEffect 時)並在 windows 中顯示結果,但我嘗試以一種方式設計我單擊按鈕,然后它將獲取 API

3-當在 onsubmit 表單中調用 credentialVerify function 時,我有 console.log(e) 但它顯示為未定義,但據我所知,onsubmit 將調用 function 並默認通過 event 參數。

下面是我的代碼片段。

任何幫助表示贊賞。

import React, { useState, useEffect } from "react";
    import "../App.css";
    import { Link } from "react-router-dom";

    function Signin() {
      const [name, setName] = useState("");
      const [password, setPassword] = useState("");
      const updateName = (e) => {
        setName(e.target.value);
      };
      const updatePassword = (e) => {
        setPassword(e.target.value);
      };
      const [items, setItems] = useState([]);
      useEffect(() => {              //Point-1  useEffect- API not call atall without this statement
        credentialVerify();
      }, []);
      const credentialVerify = async (e) => {
        console.log(e);                                         //Point-3 this is coming as undefined
        const data1 = await fetch("http://localhost:5000/api/customers");
        const incomingdata = await data1.json();
        console.log(data1);
        console.log(incomingdata);
        console.log(name, password);
        setItems(incomingdata);
      };
      return (
        <div>
          <div>
            {
              <form className="formstyle" onSubmit={credentialVerify}>
                <input
                  type="text"
                  placeholder="Username"
                  name="username"
                  value={name}
                  onChange={updateName}
                />
                          
                <input
                  type="text"
                  placeholder="Password"
                  name="password"
                  value={password}
                  onChange={updatePassword}
                />
                <button type="submit">Submit</button>
              </form>
            }
          </div>
          <div>
           
            {items.map((entry) => {
              let key = entry.email;
              let valuefirst = entry.firstName;
              let valuelast = entry.created_at;
            
              return (
                <p key={key}>
                  {key}: {valuefirst}bb {valuelast}
                </p>
              );
            })}
          </div>
        </div>
      );
    }
    export default Signin;

對於您的第一個問題,您是正確的 - 在您的組件第一次呈現時調用credentialVerify是沒有意義的,因為這似乎是您提交表單時的處理程序。 除非您在顯示表單之前獲取數據,否則您可以完全放棄useEffect掛鈎。

這也解決了您的第二個問題,因為該掛鈎將在您的組件第一次呈現時運行一次,這由用作useEffect掛鈎的依賴數組的空數組[]指示。 這相當於class-based componentDidMount中的 componentDidMount,但同樣,此時調用credentialVerify沒有意義。

至於您的第三個問題,您可能應該執行以下操作:

const credentialVerify = event => {
  event.preventDefault();

  (async () => {
    const data = await fetch("http://localhost:5000/api/customers")
      .then(res => res.json());
      .catch(e => e);
    console.log(incomingData);
    // ...
  })();
}

由於您將異步 function 作為事件處理程序傳遞,因此由於React文檔中所述的原因,您在訪問SyntheticEvent object 時可能會遇到問題:

SyntheticEvent 是池化的。 這意味着 SyntheticEvent object 將被重用,並且在調用事件回調后所有屬性都將無效。 這是出於性能原因。 因此,您不能以異步方式訪問事件。


您的最終組件應如下所示:

function Signin() {
  const [name, setName] = useState("");
  const [password, setPassword] = useState("");
  const [items, setItems] = useState([]);
  const updateName = e => {
    setName(e.target.value);
  };
  const updatePassword = e => {
    setPassword(e.target.value);
  };
  const credentialVerify = event => {
    event.preventDefault();

    (async () => {
      const incomingdata = await fetch("http://localhost:5000/api/customers")
        .then(res => res.json())
        .catch(e => e);
      console.log(incomingdata);
      console.log(name, password);
      setItems(incomingdata);
    })();
  };
  return (
    <div>...</div>
  );
}

暫無
暫無

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

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