只有一个依赖项的 useEffect / React Hook useEffect 缺少依赖项:'props'

useEffect with only one dependency / React Hook useEffect has a missing dependency: 'props'

我希望能够将我的输入表单重新用作编辑表单,因此在表单组件中我检查 url 中是否有 id { useParams },如果有,使用我从函数 getContact 获得的数据设置输入字段的状态,该函数通过 props.

传递

在 UseEffect 中我想跟踪 id 而不是 props,所以我只输入 [id] 作为 useEffect 结束时的依赖项。如果我添加 [id, props] 我无法设置输入字段的状态,因为它会立即将其设置回我从 getContact 返回的值()(因为如果我正在编辑,则有一个 id)。

我是 React 的新手,所以我想知道是否有更好的方法来做到这一点,或者我是否应该把 // eslint-disable-next-line 在我的代码中继续我的生活:-)

    const Form = (props) => {
      const { id } = useParams();
    
      const [input, setInput] = useState({});
    
      useEffect(() => {
        setInput(id ? props.getContact(id) : {});
      }, [id]);
    
      const handleChange = (event) => {
        let value = event.target.value;
        let name = event.target.name;
    
        setInput((prev) => {
          return { ...prev, [name]: value };
        });
      };

... A few more functions and then a return that spits out som JSX

useEffect 中使用的任何内容都应添加到依赖项数组中。为什么不像这样提取要设置的 ID?

const contectId = id ? props.getContact(id) : {};
useEffect(() => {
    setInput(contectId);
  }, [contectId]);

这仅在您将 {} 存储在渲染时不会更改的位置时有效: 要么像这样:

const emptyArray = React.useMemo(() => {}, [])
const contectId = id ? props.getContact(id) : emptyArray;
useEffect(() => {
    setInput(contectId);
  }, [contectId]);

const emtyArray = {};
const Form = (props) => {
  const { id } = useParams();

  const [input, setInput] = useState({});

 const contectId = id ? props.getContact(id) : emtyArray;
  useEffect(() => {
    setInput(contectId);
  }, [contectId]);

  const handleChange = (event) => {
    let value = event.target.value;
    let name = event.target.name;

    setInput((prev) => {
      return { ...prev, [name]: value };
    });
    console.log(input);
   };