reactjs只处理最后一个api请求数据



我有一个react表,它有多个函数,比如sort,许多过滤器也会搜索输入。当我对这些过滤器进行任何更改时,我实际上是在发出API请求。对于每一个请求,我都有两个状态{即加载和数据}。当发出请求时,加载标志变为TRUE,并且旋转组件替换表中的数据。当我们开始得到任何响应时,加载标志将是False

问题:当我更改多个过滤器时,它将发出多个API调用/请求。响应将异步返回,因此表在显示最后一个响应数据几分钟后开始显示第一个响应数据。

我想要实现的:我想要忽略所有请求,只处理最后一个请求。

我不久前遇到了一个与您类似的问题。我在lodash库中使用了去抖动技术,效果很好。如果没有其他挂起的,debounce函数会发出请求指定时间内的请求(此处为1秒(

import _ from "lodash";
const debounce = useCallback(
_.debounce(() => {
// Call a function here to make the api request
getData('yourApiUrl');
}, 1000),
[]
);

useCallback钩子只允许此函数在其依赖项更改时进行更新。现在我使用的是一个空数组,但您可以在其中放入任何与过滤器相关的状态值。

useEffect(() => {
if(conditionToCall){
debounce();
return debounce.cancel;
}
}, [lastFilter]);

在上面的useEffect中,只有当您的标志为true时,您才能触发此反跳功能,并取消其余功能。现在,当只将最后一个过滤器传递给api调用时,可以做的一件事是保留一个useState钩子,每次更改时都会更新到最新的过滤器。在useEffect中,将其更新为当前版本,如下所示:

const [lastfilter, setLastFilter] = useState('default');
useEffect(() => {
//set the state to whatever filter value gets triggered
setLastFilter(currentFilter);
//Remember to pass dependencies 
//to this array so it runs everytime a relevant
//piece of state updates.
}, [dependencies]);

重要的是,我将示例lastFilter钩子添加到useEffect依赖数组中,用于调用debounce函数。这允许它在每次更新该值时运行。有了这些东西的结合,我希望你能够朝着正确的方向前进!

您可以使用react类生命周期的getDerivedStateFromProps属性从state中获取最新更新的数据"数据";。

static getDerivedStateFromProps(props, state) {
...
}

只需使用useRef即可完成。

  • 在每次按键或输入更改时,将搜索文本值存储在useRef变量中
  • 进行API调用,该调用将使用本地";文本值">
  • 一旦API调用返回了"0"的结果;文本值";(async(,仅当";文本值";与CCD_ 5值匹配。表示这是最新的结果
import React, { useState, useRef } from "react";
// React Component that will be rendered onto the page
export default function App() {
const [text, setText] = useState("");
const [results, setResult] = useState("");
const currentText = useRef("");
// term is not shared amongst multiple invocations
const handleChange = async (term) => {
setText(term);
currentText.current = term;
if (term) {
const res = await searchAPI(term);
// update state only if it's the latest api cll
if (currentText.current === term) {
console.log("update from latest api call");
setResult(res);
} else {
console.log("ignore old api call");
}
} else {
setResult("");
}
};
return (
<div>
<input
value={text}
placeholder="enter search term"
onChange={(e) => handleChange(e.target.value)}
/>
<div> results: {results}</div>
</div>
);
}

最新更新