简体   繁体   English

State 变量未在 onClickHandler 中更新,同时使用 Hooks 通过用户在反应中输入从 API 获取数据

[英]State variable is not updated in onClickHandler while using Hooks for getting data from an API by a user input in react

import React, { useState } from "react";

export default function EmpInfo() {
  const [url, setUrl] = useState(
    "http://dummy.restapiexample.com/api/v1/employees/"
  );
  const [data, setData] = useState(null);
  const [input, setInput] = useState("");

  function onChangeHandler(event) {
    setInput(event.target.value);
  }

  function onClickHandler() {
    console.log("Input -> " + input);

    //Input is working as expected

    setUrl(url => url + input);
    getDataFromUrl(url);
  }

  function getDataFromUrl(url) {
    console.log(" URL ->" + url);

    // here the input value is not added to the url

    fetch(url)
      .then(response => {
        if (response.ok) {
          response.json();
        } else {
          throw new Error("Something went wrong");
        }
      })
      .then(data => {
        setData(data);
      })
      .catch();
  }
  return (
    <div>
      <table>
        <tbody>
          <tr>
            <td>
              <h4>Enter Employee ID </h4>
            </td>
            <td>
              <input type="text" placeholder="ID" onChange={onChangeHandler} />
            </td>
            <td>
              <input type="button" onClick={onClickHandler} value="Search" />
            </td>
          </tr>
        </tbody>
      </table>
      <h4>{url}</h4>

      //Here the updated URL with the input added to it is displayed as I click the Button

    </div>
  );
}

React hooks are executing asynchronously. React 钩子是异步执行的。 When you call setUrl , it will be executed in the next cycle and when you call getDataFromUrl , your setUrl is not executed yet.当您调用setUrl时,它将在下一个循环中执行,而当您调用getDataFromUrl时,您的setUrl尚未执行。 you should pass the new url manually to getDataFromUrl您应该手动将新的 url 传递给getDataFromUrl

function onClickHandler() {
    console.log("Input -> "+input)
    setUrl(url =>
        url + input
    )
    getDataFromUrl(url+input)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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