React useState和useEffect状态落后一步



我知道,出于性能原因,对状态的更新是异步和批量的。我知道我选择使用useState((和useEffect((来等待我的状态更新,然后采取行动。我的问题是我的状态总是比它应该的状态落后一步。

const myFunctionalComponent: React.FC<Props> = (
props: Props
) {
const [lastRequestURL, setLastRequestURL] = useState<string>();
useEffect(() => {
if (lastRequestURL !== undefined) {
(async () => {
try {
await webRequest(lastRequestURL);
} catch (e) {
setResponse(undefined);
}
})();
}
}, [lastRequestURL]);
const webRequest = async (value: string) => {
const response = await axios.get(createURL(`/myServer/website-to-query?url=${encodeURIComponent(value)}`);
// I do operations server-side with value (a URL) and then send a response back
if (response) {
if (newResponse.data.URL &&
lastRequestURL !== newResponse.data.URL) { // I send the URL back in the data
return; // This guard check is the key functionality that I want to work. 
// I check the URL that was used for the request vs. the most recent 
// URL that a handle change call has received. If it is not the same, 
// that means that I've don't want to display anything as that 
// info from the server is already invalid with the front-end's new state
}
// Do stuff that is valid for the front-end b/c we passed the check
}
}
const handleChange = async (value: string): Promise<void> => {
setLastRequestURL(value);
};

谢谢你的帮助。

免责声明:我认为这不是一个好的做法,但如果你真的需要的话\_(ツ)_/’,您也可以查看axios的请求取消

您可以使用ref来存储可变变量,因此它将独立于反应生命周期

const myFunctionalComponent: React.FC<Props> = (
props: Props
) {
const lastRequestURL = useRef<string>(undefined);
const webRequest = async (value: string) => {
const response = await axios.get(createURL(`/myServer/website-to-query?url=${encodeURIComponent(value)}`);
// I do operations server-side with value (a URL) and then send a response back
if (response) {
if (newResponse.data.URL &&
lastRequestURL.current !== newResponse.data.URL) { // I send the URL back in the data
return; // This guard check is the key functionality that I want to work. 
// I check the URL that was used for the request vs. the most recent 
// URL that a handle change call has received. If it is not the same, 
// that means that I've don't want to display anything as that 
// info from the server is already invalid with the front-end's new state
}
// Do stuff that is valid for the front-end b/c we passed the check
}
}
const handleChange = async (value: string): Promise<void> => {
await webRequest(value);
lastRequestURL.current = value;
};
}

https://www.emgoto.com/storing-values-with-useref/

最新更新