Estoy tratando de seleccionar aleatoriamente una imagen para mostrar en ReactJS ( NO React Native ). Estaba tratando de basar esto en otra pregunta, pero estoy confundido y no estoy seguro de cómo solucionar este error. Aquí está mi código en RandomWelcomePicture.js . Soy un poco nuevo en esto, así que lo siento si esto es una solución fácil.
import React, { useState } from 'react'; import image2019_0201 from '../images/2019_0201.jpeg'; import image2019_0202 from '../images/2019_0202.jpeg'; import image2019_0203 from '../images/2019_0203.jpeg'; const images = [ image2019_0201, image2019_0202, image2019_0203, ]; class RandomWelcomePicture extends React.Component { state = { currentImageIndex: Math.floor(Math.random() * images.length } componentDidMount() { this.changeImage(); } changeImage = () => { const randomNumber = Math.floor(Math.random() * images.length); this.setState({ currentImageIndex: randomNumber }); } render() { return ( <image source={images[this.state.currentImageIndex]} //style={styles.imageStyle} /> ) } }Aquí está mi error:
ERROR in ./src/components/RandomWelcomePicture.js Module build failed (from ./node_modules/babel-loader/lib/index.js): SyntaxError: RandomWelcomePicture.js: Unexpected token, expected "," (13:74) 11 | 12 | class RandomWelcomePicture extends React.Component { > 13 | state = { currentImageIndex: Math.floor(Math.random() * images.length } | ^ 14 | 15 | componentDidMount() { 16 | this.changeImage();Pero no creo que deba haber una coma allí. ¿Hay algo más que me estoy perdiendo?
Su problema es combinar una clase React.Component y un componente funcional en uno. Veamos el código línea por línea para verlo más claro
export default function RandomWelcomePicture() { // -------------^---------------- functional syntax (its a function) componentDidMount() { // ---------^---------------- class syntax (defining a method) this.changeImage(); } changeImage = () => { // ---^---------------- class syntax (defining a method) const randomNumber = Math.floor(Math.random() * images.length); this.setState({ // ---^---------------- class syntax (setState) currentImageIndex: randomNumber }); } return ( // -^---------------- functional syntax (return jsx vs render method) <Image source={images[this.state.currentImageIndex]} style={styles.imageStyle} /> ) }Ahora veamos cómo podemos cambiar esto para que funcione de manera funcional y como componente de clase.
No necesita tener un componenteDidMount para hacer lo que está tratando de hacer aquí ... simplemente pase eso como un valor inicial a su estado.
export default function RandomWelcomePicture() { const [currentImageIndex, setCurrentImageIndex] = useState(Math.floor(Math.random() * images.length)) const changeImage = () => { const randomNumber = ; setCurrentImageIndex(randomNumber); } useEffect(() => changeImage(), []) return ( <Image source={images[currentImageIndex]} style={styles.imageStyle} /> ) }si realmente necesita un componenteDidMount en un componente funcional, debe hacer esto
useEffect(() => changeImage(), []) // empty array means this effect only runs once which is the same thing as componentDidMount class RandomWelcomePicture extends React.Component { state = { currentImageIndex: Math.floor(Math.random() * images.length } componentDidMount() { this.changeImage(); } changeImage = () => { const randomNumber = Math.floor(Math.random() * images.length); this.setState({ currentImageIndex: randomNumber }); } render() { return ( <Image source={images[this.state.currentImageIndex]} style={styles.imageStyle} /> ) } }