gpt4 book ai didi

javascript - Lodash 去抖异步/等待

转载 作者:行者123 更新时间:2023-12-03 06:58:11 25 4
gpt4 key购买 nike

在进行 api 调用之前,我正在尝试为我的应用程序添加去抖动功能。但是,当我介绍 debouce 时,似乎我的 await 被忽略了,并且由于缺少值而导致函数调用

export default class App extends Component {
state = {
search: "Cats",
results: []
};

async search(text) {
const giphy = {
baseURL: "https://api.giphy.com/v1/gifs/search",
apiKey: "0UTRbFtkMxAplrohufYco5IY74U8hOes",
tag: text
};

let giphyURL = encodeURI(
giphy.baseURL + "?api_key=" + giphy.apiKey + "&q=" + giphy.tag
);

let data = await fetch(giphyURL);
return data.json();
}

async componentDidMount() {
// get default search
this.onSearch(this.state.text);
}

setSearch = e => {
this.setState({ search: e.target.value });

debounce(() => this.onSearch(this.state.search), 100);
};

async onSearch(text) {
console.log("text:", text);
try {
let response = await this.search(this.state.search);
console.log("data:", response.data);
// console.log(data.results);

let data = response.data.reduce((t, { title, id, images }) => {
t.push({ title, id, url: images.downsized_medium.url });
return t;
}, []);
this.setState({ results: data });
} catch (e) {
console.error("Failed Fetch", e.toString());
}
}

render() {
return (
<main className="app">
<Header>This is my Gif Search App</Header>
<nav className="navbar">
<SearchBox onSearch={this.setSearch} value={this.state.search} />
</nav>
<aside className="sidebar">Sidebar Bar</aside>
<section className="results">
<Results results={this.state.results} />
</section>
<footer className="footer">
<p className="footer-text">Copyright @funssies 2019</p>
</footer>
</main>
);
}
}

错误:在 setSearch 方法中,我在 debounce 中包装了获取数据的调用,但没有任何 react 。

最佳答案

我想我想通了。 Deboune 返回一个函数。然后我必须调用该函数

例如:

let myFunc = debounce(this.someFunction,100)

// call debounced function
myFunc()

我将我的功能更改为:
  delayedSearch = debounce(this.onSearch, 1500);

setSearch = e => {
this.setState({ search: e.target.value });

this.delayedSearch(this.state.search);
};


在这里找到帮助: lodash debounce not working in anonymous function

关于javascript - Lodash 去抖异步/等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58055085/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com