[英]Use useEffect to manage the state in React
我编写了一个程序,从数组中获取和显示contacts
,我们有一个用于在联系人之间搜索的input
,我们输入并显示结果。 我用if
在搜索功能,以检查if
该searchKeyword
变化,记得做了filter
else
,它并没有改变, return contacts
并没有过滤器做我想做的事与此控件useEffect
和我评论了我写的部分useEffect
。 请帮助我达成使用useEffect
的解决方案。 谢谢你。
实际上,我想使用useEffect
而不是if
我把我的代码放在下面的链接中
https://codesandbox.io/s/simple-child-parent-comp-forked-4qf39?file=/src/App.js:905-913
在您的沙箱中的useEffect
钩子中,您实际上并未更新任何状态。
useEffect(()=>{
const handleFilterContact = () => {
return contacts.filter((contact) =>
contact.fullName.toLowerCase().includes(searchKeyword.toLowerCase())
);
};
return () => contacts;
},[searchKeyword]);
你正在从useEffect
钩子返回一个值,它被 React 解释为一个钩子清理函数。
请参见清理效果
将状态添加到MainContent
以保存过滤后的联系人数组。 将filtered
状态传递给Contact
组件。 您可以使用相同的handleFilterContact
函数来计算过滤状态。
const MainContent = ({ contacts }) => {
const [searchKeyword, setSearchKeyword] = useState("");
const [filtered, setFiltered] = useState(contacts.slice());
const setValueSearch = (e) => setSearchKeyword(e.target.value);
useEffect(() => {
const handleFilterContact = () => {
if (searchKeyword.length >= 1) {
return contacts.filter((contact) =>
contact.fullName.toLowerCase().includes(searchKeyword.toLowerCase())
);
} else {
return contacts;
}
};
setFiltered(handleFilterContact());
}, [contacts, searchKeyword]);
return (
<div>
<input
placeholder="Enter a keyword to search"
onChange={setValueSearch}
/>
<Contact contacts={contacts} filter={filtered} />
</div>
);
};
我建议不要将过滤的联系人数组存储在 state 中,因为它很容易从传递的contacts
prop 和本地searchKeyword
状态派生而来。 您可以内联过滤。
const MainContent = ({ contacts }) => {
const [searchKeyword, setSearchKeyword] = useState("");
const setValueSearch = (e) => setSearchKeyword(e.target.value);
const filterContact = (contact) => {
if (searchKeyword.length >= 1) {
return contact.fullName
.toLowerCase()
.includes(searchKeyword.toLowerCase());
}
return true;
};
return (
<div>
<input
placeholder="Enter a keyword to search"
onChange={setValueSearch}
/>
<Contact contacts={contacts.filter(filterContact)} />
</div>
);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.