繁体   English   中英

在 React 中使用 useEffect 来管理状态

[英]Use useEffect to manage the state in React

我编写了一个程序,从数组中获取和显示contacts ,我们有一个用于在联系人之间搜索的input ,我们输入并显示结果。 我用if在搜索功能,以检查ifsearchKeyword变化,记得做了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>
  );
};

编辑 use-useeffect-to-manage-the-state-in-react

建议

我建议不要将过滤的联系人数组存储在 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM