[英]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.