我已经使用两个状态变量来过滤颜色search, resultantColors
。
现有的 useEffect 会监视输入中的搜索,然后设置过滤后的数组。但这些效果会在每次输入更改时运行,我如何才能将 useEffect 重构为 useMemo,以便能够减少重新渲染?
另外,由于我们想要重构现有的 useEffect(组件 DidUpdate 生命周期),useMemo 是否支持 componentDidMount(空数组依赖项)、componentWillUnmount 的所有生命周期方法? ——对这个可以回答是或否。
我尝试减少重新渲染,但对于此示例,useEffect 会在每次更改时运行,每次都会触发。此外,useMemo 是否处理 useEffect 的所有等效生命周期?
import { useEffect, useState } from 'react';
function App() {
const mockColors = ['white', 'blue', 'yellow', 'green', 'orange', 'purple'];
const [search, setSearch] = useState('');
const [resultantColors, setResultantColors] = useState(mockColors);
const handleInputChange = (e) => {
setSearch(e.target.value);
};
useEffect(() => {
if (search == '') {
setResultantColors(mockColors);
} else {
const resultColors = resultantColors.filter((color) =>
color.toLowerCase().includes(search.toLowerCase())
);
setResultantColors(resultColors);
}
}, [search]);
return (
<div style={{ border: '1px solid blue', padding: 20, margin: 20 }}>
Filter Example with UseEffect <br />
<label htmlFor="colors">Filter Color:</label>
<input
type="search"
name="search"
value={search}
id="colors"
onChange={(e) => {
handleInputChange(e);
}}
placeholder="filter colors"
/>
{resultantColors.length > 0 ? (
resultantColors.map((value, index) => (
<>
<li key={`${value} + ${index}`}>{value}</li>
</>
))
) : (
<p>No items - search existing value </p>
)}
</div>
);
}
export default App;