gpt4 book ai didi

javascript - 在 react 中使用 'useMemo' 时只在数组中显示匹配的字符串

转载 作者:行者123 更新时间:2023-12-04 07:23:18 25 4
gpt4 key购买 nike

我有一个自动完成输入字段,并在最初将输出隐藏在我的数组中时遇到问题。我只想显示匹配的字符串,而不是在安装时显示我的所有项目。让我的状态为空 const [filteredRecipes, setFilteredRecipes] = useState();会在我的循环中出错。
密码箱:
https://codesandbox.io/s/quzwg?file=/App.js:251-313
JS:

export default function App() {
const items = useMemo(
() => ["item1", "item2", "anotheritem", "yetanotheritem", "myitem"],
[]
);

const [search, setSearch] = useState("");
const [filteredRecipes, setFilteredRecipes] = useState(items);

const handleSearchChange = event => {
setSearch(event.target.value);
};

useEffect(() => {
setFilteredRecipes(
items.filter(el => el.toLowerCase().includes(search.toLowerCase()))
);
}, [search, items]);

return (
<div>
<input
type="search"
placeholder="type here to filter"
value={search}
onChange={handleSearchChange}
/>
<div>
{filteredRecipes.map(recipe => (
<p>{recipe}</p>
))}
</div>
</div>
);
}

最佳答案

如果我正确理解你的问题,在你的例子中 filteredRecipes是您希望在安装时最初隐藏的自动完成建议,或者在此处进行假设,只要搜索值为 false。您可以通过对 search 进行条件过滤来做到这一点。状态为真/假。所有字符串都将包含空字符串 ( '' ),因此您希望以不同方式处理这种情况。

setFilteredRecipes(
search
? items.filter((el) => el.toLowerCase().includes(search.toLowerCase()))
: []
);
代码
export default function App() {
const items = useMemo(
() => ["item1", "item2", "anotheritem", "yetanotheritem", "myitem"],
[]
);

const [search, setSearch] = useState("");
const [filteredRecipes, setFilteredRecipes] = useState([]);

const handleSearchChange = (event) => {
setSearch(event.target.value);
};

useEffect(() => {
setFilteredRecipes(
search
? items.filter((el) => el.toLowerCase().includes(search.toLowerCase()))
: []
);
}, [search, items]);

return (
<div>
<input
type="search"
placeholder="type here to filter"
value={search}
onChange={handleSearchChange}
/>
<div>
{filteredRecipes.map((recipe) => (
<p>{recipe}</p>
))}
</div>
</div>
);
}
Edit only-show-matching-string-in-array-when-using-usememo-in-react

关于javascript - 在 react 中使用 'useMemo' 时只在数组中显示匹配的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68368566/

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