延迟 React 中的 STATE 更改
Delay STATE change in React
我正在写一个网站。这是一个使用股票并从中获取数据的网站 API 来显示股票价格和图表。
我有一个搜索栏,只要输入一个字母就会改变状态。但是,它会引起问题,因为它会立即更新状态,然后从 API 获取数据,例如,如果我输入 Z - 然后 API 正在寻找名为“Z”的股票
然后应用程序崩溃,变成空白(因为 link 不存在)。我实际上必须复制股票名称,例如“AAPL”,然后粘贴它 - 应用程序才能正常工作。
var baseUrl = `https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=${search}&apikey=**********`;
因为“搜索”状态已更新并且正在搜索该股票/
无论如何,这是我的股票搜索栏组件。
const StockSearchBar = () => {
const { search, setSearch } = useContext(SearchContext); // i'm using context API to store state so I can access it across different components
const handleClick = (e) => {
if (setSearch !== '') { // if there's something in state, then post data to backend
const options =
{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({search}),
};
const response = fetch(`http://localhost:3001/api/search`, options);
};
function handleButtonEvents(e) { // i'm using a function to chain handleClick() and setTimeout() to be run when button is clicked
e.preventDefault();
handleClick();
setTimeout(() => window.location.reload(), 3000); // delay the function for 3 seconds to give it time to fetch the data and display it, otherwise it might refresh the page without updating it with new data
}
const handleSearch = e => {
e.preventDefault();
setSearch(e.target.value.toUpperCase()); // i think the problem is here - i need to delay setting state
}
return (
<>
<div className="searchBar">
<label>Look for Stocks or Cryptos: </label>
<input type='text' onChange={handleSearch} onKeyPress={(ev) => {
if (ev.key === "Enter") { handleButtonEvents(); }}}
{/* search if Enter key is pressed */} // i think the problem is with **onChange** or the handleSearch **function** but not sure how to deal with it
placeholder={search} required />
<Button variant="success" type="submit" onClick={handleButtonEvents} >Search</Button>
</div>
<h1 className="src">{search}</h1>
{// display state to see if it's changing ( just testing }
</>
);
};
export default StockSearchBar;
如果您想查看上下文 API 文件或其他内容,请告诉我。但我认为问题在搜索栏组件中。
提前感谢您的帮助。
您需要使用 Debounce
来创建延迟,例如来自 lodash。所以在你的情况下是
const handleSearch = e => {
e.preventDefault();
debounce(setSearch(e.target.value.toUpperCase()), 500)// debounce 500 milliseconds
}
我正在写一个网站。这是一个使用股票并从中获取数据的网站 API 来显示股票价格和图表。
我有一个搜索栏,只要输入一个字母就会改变状态。但是,它会引起问题,因为它会立即更新状态,然后从 API 获取数据,例如,如果我输入 Z - 然后 API 正在寻找名为“Z”的股票 然后应用程序崩溃,变成空白(因为 link 不存在)。我实际上必须复制股票名称,例如“AAPL”,然后粘贴它 - 应用程序才能正常工作。
var baseUrl = `https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=${search}&apikey=**********`;
因为“搜索”状态已更新并且正在搜索该股票/
无论如何,这是我的股票搜索栏组件。
const StockSearchBar = () => {
const { search, setSearch } = useContext(SearchContext); // i'm using context API to store state so I can access it across different components
const handleClick = (e) => {
if (setSearch !== '') { // if there's something in state, then post data to backend
const options =
{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({search}),
};
const response = fetch(`http://localhost:3001/api/search`, options);
};
function handleButtonEvents(e) { // i'm using a function to chain handleClick() and setTimeout() to be run when button is clicked
e.preventDefault();
handleClick();
setTimeout(() => window.location.reload(), 3000); // delay the function for 3 seconds to give it time to fetch the data and display it, otherwise it might refresh the page without updating it with new data
}
const handleSearch = e => {
e.preventDefault();
setSearch(e.target.value.toUpperCase()); // i think the problem is here - i need to delay setting state
}
return (
<>
<div className="searchBar">
<label>Look for Stocks or Cryptos: </label>
<input type='text' onChange={handleSearch} onKeyPress={(ev) => {
if (ev.key === "Enter") { handleButtonEvents(); }}}
{/* search if Enter key is pressed */} // i think the problem is with **onChange** or the handleSearch **function** but not sure how to deal with it
placeholder={search} required />
<Button variant="success" type="submit" onClick={handleButtonEvents} >Search</Button>
</div>
<h1 className="src">{search}</h1>
{// display state to see if it's changing ( just testing }
</>
);
};
export default StockSearchBar;
如果您想查看上下文 API 文件或其他内容,请告诉我。但我认为问题在搜索栏组件中。
提前感谢您的帮助。
您需要使用 Debounce
来创建延迟,例如来自 lodash。所以在你的情况下是
const handleSearch = e => {
e.preventDefault();
debounce(setSearch(e.target.value.toUpperCase()), 500)// debounce 500 milliseconds
}