javascript - 搜索输入反应 JS
问题描述
我正在使用黑客新闻 API 构建一个具有反应的应用程序。我正在尝试按标题搜索我的故事,但似乎无法正常工作。有没有办法像访问数组一样访问所有 Story 组件,以便我可以过滤?
工作版本在这里
我知道如何处理从输入中获取值并使用它来过滤数组的搜索事件。问题是我不确定如何访问已经在屏幕上呈现的故事数组
对不起,如果有些东西没有意义,我还在学习,有点困惑。
// APICALLs file
// Return a promise with all new stories IDs
export const getStoryIds = async (url) => {
const response = await axios.get(url).then((data) => data);
return response.data;
};
// Return a promise with a story item
export const getStory = async (storyId) => {
const response = await axios
.get(`${storyUrl + storyId}.json`)
.then((data) => data);
return response.data;
};
//Main container where I render all stories
import { Fragment, useEffect, useState } from "react";
import { GlobalStyle } from "../styles/GlobalStyles";
import {
getStoryIds,
newStoriesUrl,
bestStoriesUrl,
showStoriesUrl,
jobStoriesUrl,
} from "../services/Api";
import { Story } from "./Story";
import { useInfiniteScroll } from "../hooks/useInfiniteScroll";
import {
StoriesContainerStyle,
ContainerTitle,
} from "../styles/StoriesContainer";
import { ButtonContainerStyle } from "../styles/ButtonContainer";
import { ButtonStyle } from "../styles/ButtonStyle";
export const StoriesContainer = () => {
const count = useInfiniteScroll();
const [storyIds, setStoryIds] = useState([]);
const [filter, setFilter] = useState([]);
const handleClick = (url) => (event) => {
getStoryIds(url).then((data) => setStoryIds(data));
};
useEffect(() => {
getStoryIds(newStoriesUrl).then((data) => setStoryIds(data));
}, []);
return (
<Fragment>
<GlobalStyle />
<StoriesContainerStyle>
<ContainerTitle>Hacker News</ContainerTitle>
<ButtonContainerStyle>
<ButtonStyle onClick={handleClick(newStoriesUrl)}>New</ButtonStyle>
<ButtonStyle onClick={handleClick(bestStoriesUrl)}>Best</ButtonStyle>
<ButtonStyle onClick={handleClick(showStoriesUrl)}>Show</ButtonStyle>
<ButtonStyle onClick={handleClick(jobStoriesUrl)}>Jobs</ButtonStyle>
</ButtonContainerStyle>
{storyIds.slice(0, count).map((storyId) => (
<Story key={storyId} storyId={storyId} />
))}
</StoriesContainerStyle>
</Fragment>
);
};
//Story Component
import { useState, useEffect, memo } from "react";
import { getStory } from "../services/Api";
import { StoryCard, StoryDetail, StoryTitle } from "../styles/StoryStyle";
import { formatTime } from "../utils/formatTime";
export const Story = memo(function Story({ storyId }) {
const [story, setStory] = useState([]);
useEffect(() => {
getStory(storyId).then((data) => setStory(data));
}, []);
return story && story.url ? (
<StoryCard href={story.url} target="_blank" rel="noreferrer">
<StoryTitle>{story.title}</StoryTitle>
<StoryDetail>
By: {story.by} | Posted: {formatTime(story.time)}
</StoryDetail>
</StoryCard>
) : null;
});
解决方案
https://codesandbox.io/embed/react-hooks-search-filter-4gnwc
我的工作代码(看起来与链接中的非常相似):
useEffect (() => {
dispatch(retrieveDevices())
// eslint-disable-next-line
}, []);
useEffect(() => {
const results = devices.filter(device => device.deviceId.toString().toLowerCase().includes(searchTitle.toLowerCase()));
setSearchResults(results);
}, [devices, searchTitle]);
我的原始代码导致 SQL 查询无限循环(一遍又一遍地获取请求......):
useEffect(() => {
const results = devices.filter(device => device.deviceId.toString().toLowerCase().includes(searchTitle.toLowerCase()));
setSearchResults(results);
if (!searchTitle) {
dispatch(retrieveDevices())
}
}, [dispatch, searchTitle, devices]);
此外,如果您的变量是字符串,您可能需要添加“toString()”。(编辑)在第一个“toLowerCase()”之前。否则它将无法正确传递格式。
此外,从那个链接,列表代码有点接近我的:
{filteredCountries.map((country, idx) => (
<CountryDetail key={idx} {...country} />
))}
但是从我在今天工作之前的以前的存储库中,并且只编辑了一个与以前版本不同的单词,这就是我如何正确呈现我的列表并且与该示例完全一样的工作方式(编辑:这保持不变):
{devices &&
searchResults.map((device, index) =>
编辑:得到我的代码并替换代码示例甚至修改,因为我为自己创建了一个无限循环(哎呀)
推荐阅读
- laravel - 如何在 laravel queue.php 中设置多个队列
- python - 编译 tf.keras 模型时可以使用哪些指标?
- python - 通过装饰器动态添加函数到类
- bash - 如何在 bash 中执行一个不是孩子并继续运行的应用程序?
- javascript - 带要求的动态变量
- .net - 来自前端 UI 的查询的微服务通信
- javascript - 为什么我的 Ajax 请求包含数据类型:“jsonp”错误?
- python - 相同数学运算的不同结果
- javascript - Javascript Fetch:错误 Unexpected token < in JSON at position 0
- phpstorm - Xdebug - PhpStorm 在其他进程上中断,但不是原始运行配置