Nuevo en RJS, tratando de acceder a mi variable "txt" fuera de la devolución de llamada de Data.map donde se declaró originalmente, ¿cómo podría hacer esto y tener acceso completo a la variable?
import Data from "./names.json"; export default function App() { //want to access txt in here <============== // console.log(txt) and stuff after accessing it here return ( <div className="App"> {Data.map((post) => { var txt = post.Name; return <h1>{post.Name}</h1>; })} </div> ); }Gracias
De muchas formas, pero el gancho useState es bastante sólido, especialmente si quieres aprovechar la velocidad de React.
import Data from "./names.json"; export default function App() { const [ txt, setTxt ] = useState(""); // sets it to an empty string to begin with useEffect(() => { console.log(txt); // every time the 'txt' variable changes, log it }, [ txt]); // << React calls this a dependency and will only run this function when this value changes. console.log(txt); // also accessible here return ( <div className="App"> {Data.map((post) => { setTxt(post.Name); // This updates the 'txt' variable from earlier ^^ return <h1>{post.Name}</h1>; })} </div> ); } Si todo eso es demasiado largo, simplemente mantenga su variable txt fuera del componente de la función, y React no lo restablecerá en cada bucle. Aún podrá acceder a su valor en cualquier parte del archivo. Ejemplo:
import Data from "./names.json"; let txt = ""; export default function App() { return ( <div className="App"> {Data.map((post) => { txt = post.Name; return <h1>{post.Name}</h1>; })} </div> ); }Afaik, no puede porque el texto está dentro del alcance de la función de mapa y no puede acceder a él fuera de él. Puede intentar ponerlo en un estado o hacer una función y convertirla en un argumento de esa función desde dentro de la función de mapa.
import Data from "./names.json"; import {useState} from 'react' export default function App() { //want to access txt in here <============== // console.log(txt) and stuff after accessing it here const [text,setText] = useState() function getText(text) { console.log(text) // this function gets called in every instance of the map loop //you can run your logic here to find specific information and then set it to the state like in this example if (text === "myText") { setText(text) } } return ( <div className="App"> {Data.map((post) => { var txt = post.Name; getText(txt) // will run and recieve the var txt every instance return <h1>{post.Name}</h1>; })} </div> ); }