Tengo este código para obtener la entrada del usuario y enviarlo de vuelta al despacho.
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> ); }La función de agregar es esta:
const submitBookToStore = (title, author) => { const newBook = { id: uuidv4(), title, author, }; dispatch(addBook(newBook)); };Entonces veo este error:
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.¡El comportamiento extraño es que llama a onClick cuando la página se carga cuando no hice clic!
Si lo llamas así:
onClick={add(book.title, book.author)}Se ejecutará en render. Prueba esto en su lugar:
onClick={() => add(book.title, book.author)} Esto se debe a que add () indica una llamada de función donde, como en su onChange, solo está dando una función para que se llame onChange={onChange} la diferencia radica en los paréntesis ()
Prueba lo siguiente:
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> ); }Espero que eso ayude