En el siguiente código, la función GetRandomInt toma una entrada máxima de la función App . La supuesta salida console.log solo debe imprimir el valor del argumento. Pero imprime Undefined en la consola.
const GetRandomInt = ({max}) => { console.log(max) return Math.floor(Math.random() * (max)) } const Button = (props) => { return ( <button onClick={props.handleClick}> {props.text} </button> ) } const Display = (props) => { return ( <div> {props.text} </div> ) } const App = () => { const anecdotes = [ 'If it hurts, do it more often', 'Adding manpower to a late software project makes it later!', 'The first 90 percent of the code accounts for the first 10 percent of the development time...The remaining 10 percent of the code accounts for the other 90 percent of the development time.', 'Any fool can write code that a computer can understand. Good programmers write code that humans can understand.', 'Premature optimization is the root of all evil.', 'Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.', 'Programming without an extremely heavy use of console.log is same as if a doctor would refuse to use x-rays or blood tests when diagnosing patients' ] const [selected, setSelected] = useState(0) const len = anecdotes.length console.log(len) const handleClick = () => { console.log(Math.floor(Math.random() * (anecdotes.length))) const index = GetRandomInt(len) // Math.floor(Math.random() * (anecdotes.length)) while (index === selected) { index = GetRandomInt(len) // Math.floor(Math.random() * (anecdotes.length)) } setSelected(index) } return ( <div> <h1>Anecdote of the day</h1> <Display text={anecdotes[selected]} /> <Button handleClick={handleClick} text={'Next anecdote'} /> {/* {anecdotes[selected]} */} </div> ) }El código anterior imprime tres valores en la consola.
¿Alguien puede decirme por qué sucede esto? ¿Estoy pasando el valor incorrectamente, ya sea por falta de coincidencia del tipo de datos o algo así? Soy un novato en reactjs y estoy aprendiendo a través de un curso y este es uno de los ejercicios en los que estoy atascado.
La falla está en su función GetRandomInt . Actualmente espera un objeto con la propiedad max y le estás pasando un número.
Reescríbelo como
const GetRandomInt = (max) => { console.log(max) return Math.floor(Math.random() * (max)) } Lo que esencialmente hacen las llaves alrededor del nombre del parámetro es decirle a la función "Tome la propiedad max del primer argumento que se le da", mientras que en su caso desea el argumento en sí, y no su propiedad max .
Puede leer más sobre la desestructuración de objetos aquí