提问者:小点点

加载页面时如何始终调用onClick?错误:超过最大更新深度[重复]


我有这个代码来获取用户输入并将其发送回调度

import React, { useState } from 'react';

export default function Form(props) {
  const [book, setBook] = useState({
    title: '',
    author: '',
  });

  const onChange = (e) => {
    if (book[e.target.name] !== e.target.value) {
      setBook({
        ...book,
        [e.target.name]: e.target.value,
      });
    }
  };
  const { add } = props;
  return (
    <form>
      <input onChange={onChange} type="text" name="title" placeholder="Title" />
      <input onChange={onChange} type="text" name="author" placeholder="Author" />
      <button type="button" onClick={add(book.title, book.author)}>Add Book</button>
    </form>
  );
}

添加功能如下所示:

  const submitBookToStore = (title, author) => {
    const newBook = {
      id: uuidv4(),
      title,
      author,
    };
    dispatch(addBook(newBook));
  };

然后我看到这个错误:

Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops. 

奇怪的行为是,当我没有点击页面时,它在加载页面时调用onClick!!


共2个答案

匿名用户

如果你这样称呼它:

onClick={add(book.title, book.author)}

它将在渲染时运行。请尝试以下方法:

onClick={() => add(book.title, book.author)}

这是因为add()表示一个函数调用,在这里,就像在onChange中一样,你只是给一个函数调用onChange={onChange},区别在于括号()

匿名用户

请尝试以下操作:

import React, { useState } from 'react';

export default function Form(props) {
  const { add } = props;
  const [book, setBook] = useState({
    title: '',
    author: '',
  });

  const onChange = (e) => {
    if (book[e.target.name] !== e.target.value) {
      setBook({
        ...book,
        [e.target.name]: e.target.value,
      });
    }
  };
  const handleAdd = () => { add(book.title, book.author) }
  return (
    <form>
      <input onChange={onChange} type="text" name="title" placeholder="Title" />
      <input onChange={onChange} type="text" name="author" placeholder="Author" />
      <button type="button" onClick={handleAdd}>Add Book</button>
    </form>
  );
}

希望这能有所帮助