简体   繁体   English

在 React 中使用 useEffect 来管理状态

[英]Use useEffect to manage the state in React

I wrote a program that takes and displays contacts from an array, and we have an input for searching between contacts, which we type and display the result.我编写了一个程序,从数组中获取和显示contacts ,我们有一个用于在联系人之间搜索的input ,我们输入并显示结果。 I used if in the search function to check if the searchKeyword changes, remember to do the filter else , it did not change, return contacts and no filter is done I want to do this control with useEffect and I commented on the part I wrote with useEffect .我用if在搜索功能,以检查ifsearchKeyword变化,记得做了filter else ,它并没有改变, return contacts并没有过滤器做我想做的事与此控件useEffect和我评论了我写的部分useEffect Please help me to reach the solution of using useEffect .请帮助我达成使用useEffect的解决方案。 Thank you.谢谢你。

In fact, I want to use useEffect instead of if实际上,我想使用useEffect而不是if

I put my code in the link below我把我的代码放在下面的链接中

https://codesandbox.io/s/simple-child-parent-comp-forked-4qf39?file=/src/App.js:905-913 https://codesandbox.io/s/simple-child-parent-comp-forked-4qf39?file=/src/App.js:905-913

Issue问题

In the useEffect hook in your sandbox you aren't actually updating any state.在您的沙箱中的useEffect钩子中,您实际上并未更新任何状态。

useEffect(()=>{
  const handleFilterContact = () => {
    return contacts.filter((contact) =>
      contact.fullName.toLowerCase().includes(searchKeyword.toLowerCase())
    );
  };
  return () => contacts;
},[searchKeyword]);

You are returning a value from the useEffect hook which is interpreted by React to be a hook cleanup function.你正在从useEffect钩子返回一个值,它被 React 解释为一个钩子清理函数。

See Cleaning up an effect请参见清理效果

Solution解决方案

Add state to MainContent to hold filtered contacts array.将状态添加到MainContent以保存过滤后的联系人数组。 Pass the filtered state to the Contact component.filtered状态传递给Contact组件。 You can use the same handleFilterContact function to compute the filtered state.您可以使用相同的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

Suggestion建议

I would recommend against storing a filtered contacts array in state since it is easily derived from the passed contacts prop and the local searchKeyword state.我建议不要将过滤的联系人数组存储在 state 中,因为它很容易从传递的contacts prop 和本地searchKeyword状态派生而来。 You can filter inline.您可以内联过滤。

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