Quiero crear una matriz con valores aleatorios entre 0 y 7 y usar esta matriz como valor de estado, pero usarla en el bucle de llamada de componente funcional para bucle varias veces cuando el valor de estado de console.log. Esto creará un error de representación en reaccionar
import React from "react"; import "./style.css"; import { usestate} from "react" export default function App() { const [ state , setstate ] = usestate([]); let arr = [] ; for(let i = 0 ; i < 64 ; i++){ arr[i] = Math.floor((Math.random ()*8)); } setstate(arr); return ( <div> <h1>State</h1> <p>{state}</p> </div> ); }Gracias
Si usa setstate(myArrayMakingFunction) dentro de un gancho useEffect , esto debería funcionar.
Primero, necesita importar useState, en lugar de usestate. Necesita importar useEffect también o causará muchos renderizados. Su solución es el siguiente código:
import React, {useState, useEffect} from "react"; import "./style.css"; export default function App() { const [ state , setstate ] = useState([]); let arr = [] ; for(let i = 0 ; i < 64 ; i++){ arr[i] = Math.floor((Math.random ()*8)); } useEffect(()=>{ setstate(arr); }, []) return ( <div> <h1>State</h1> <p>{state}</p> </div> ); }Haga esto en la fase componentDidMount.
import React, { useState, useEffect} from 'react'; import "./style.css"; export default function App() { const [ state , setstate ] = useState([]); useEffect(()=>{ let arr = [] ; for(let i = 0 ; i < 64 ; i++){ arr[i] = Math.floor((Math.random ()*8)); } setstate(arr); }, []) return ( <div> <h1>State</h1> {state?.map(i=><p key={i}>{i}</p>)} </div> ); }