简体   繁体   中英

why is an infinite loop created?

I'm trying to create a filter on data using React hooks. I really don't understand why this code creates an infinite loop when I call setEnteredFilter. LoadedData is an array containing some objects and and I only want the objects for which the id matches what I enter in the search bar.

const [enteredFilter, setEnteredFilter] = useState("");

  useEffect(() => {
    fetch("userConf_user.json", {
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
    })
      .then(function (response) {
        return response.json();
      })
      .then(function (responseData) {
        let users = responseData.result.user;
        const loadedData = [];
        for (let obj in users) {
          loadedData.push(users[obj]);
        }
        onLoadUsers(loadedData); 

        setEnteredFilter(
          loadedData.filter((User) => {
            User === loadedData.map((user) => user.id);
          })
        ); 
      });
  }, [enteredFilter, onLoadUsers]);

  return (
    <section className="search">
      <Card>
        <div className="search-input">
          <label>search by Id: </label>
          <input
            type="text"
            value={enteredFilter}
            onChange={(Event) => setEnteredFilter(Event.target.value)}
          />
        </div>
      </Card>
    </section>
  );
});

Remove enteredFilter from the dependency array of the useEffect .

, [/* REMOVE THIS enteredFilter, */ onLoadUsers]);

The value is not referenced inside the useEffect , but because it changes the effect will run again causing the infinite loop.

I suggest using ESLint and the eslint-plugin-react-hooks plugin. It would inform you in this case that enteredFilter is not referenced in the hook and therefore should be removed from the dependency array.

So there is an infinite loop because your effect depends on enteredFilter. so when enteredFilter is modified the effect is re-run. You could remove that dependency by not including it in the array, since you are not using it anyways

When you put something in the array argument of useEffect, it's like you are telling React to 'refresh' the component whenever anything mentioned in this array changes.

So in your case, useEffect changes the value of enteredFilter , which triggers a refresh, which causes useEffect to run again, and so on and so on.

If you remove that from the array, it should work fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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