添加依赖项时useEffect无限循环

时间:2020-07-15 08:19:04

标签: reactjs redux mern

我一直在做一个MERN堆栈编辑页面,不幸的是,当我在useEffect依赖项中包含“字段”时,我遇到了无限循环,并且在删除它时工作得很好,但是

React Hook useEffect has a missing dependency: 'fields'. Either include it or remove the dependency array.

在我删除它时显示。

这里是我的代码:

 const EditFields = () => {
  const menu = useSelector((state) => state.menu.menu);
  const loading = useSelector((state) => state.loading.isLoading);
  const [fields, setFields] = useState({
    name: "",
    description: "",
    price: "",
 });

  useEffect(() => {
    if (menu) {
      setFields({
        ...fields,
        name: menu.name,
        description: menu.description,
        price: menu.price,
        dishImage: menu.dishImage,
        imgData: menu.dishImage,
      });
    }
  }, [menu,fields]);

  return (
    <>
      {!loading ? (
        <div className="add-menu">
          <p className="head">Add Menu</p>
          <form>
            <div className="add-fields">
              
              <div className="group-field">
                <label>*Menu Name</label>
                <input
                  type="text"
                  className="fileBtn"
                  placeholder="Menu Name"
                  value={fields.name}
                  onChange={(e) =>
                    setFields({ ...fields, name: e.target.value })
                  }
                  required
                />
              </div>
              <div className="group-field">
                <label>*Price</label>
                <input
                  type="number"
                  placeholder="Price"
                  value={fields.price}
                  onChange={(e) =>
                    setFields({ ...fields, price: e.target.value })
                  }
                  required
                />
              </div>
              <div className="group-field">
                <label>*Description</label>
                <textarea
                  cols="30"
                  rows="10"
                  placeholder="Menu Description"
                  value={fields.description}
                  onChange={(e) =>
                    setFields({ ...fields, description: e.target.value })
                  }
                  required
                ></textarea>
                <input type="submit" value="submit" />
              </div>
            </div>
          </form>
        </div>
      ) : (
        <h1>Loading...</h1>
      )}
    </>

1 个答案:

答案 0 :(得分:2)

在您的情况下,每次useEffect更改时都调用fields,但是在useEffect内更改fields,因此我们得到了一个无限循环。 您可以将该函数传递给setState,其第一个参数将是当前状态值。

useEffect(() => {
    if (menu) {
        setFields(prevFields => ({
            ...prevFields,
            name: menu.name,
            description: menu.description,
            price: menu.price,
            dishImage: menu.dishImage,
            imgData: menu.dishImage,
        }));
    }
}, [menu]);