¿Qué estoy tratando de hacer?
Estoy tratando de establecer una matriz de objetos en la que el valor dentro de la matriz depende del componente principal.
¿Cuál es el código que actualmente intenta hacer eso?
Aquí están los diferentes archivos simplificados:
// Parent. export default function Parent() { const [filePaths, setFilePaths] = useState(); useEffect(() => { var fileContent = JSON.parse(fs.readFileSync("./config.json"); // Reading from a JSON. var tempFilePaths = []; fileContent.FilePaths.forEach((file) => { tempFilePaths.push(file); }); setFilePaths(tempFilePaths); // Contents of "config.js" is now in the "useState". }, []); return ( <Child filePaths={filePaths}/> ) } // Child. export default function Child({filePaths}) { var links = [ { path: filePaths[0].Link1, }, { path: filePaths[0].Link2, }, ] return ( <div>Nothing here yet, but I would map those links to front-end links.</div> ) } // config.json { "url": "http:localhost:3000", "FilePaths": [ { "Link1": "C:\Documents\Something", "Link2": "C:\Documents\SomethingElse" } ] } Cuando renderizo las "filePaths" en el return() del componente secundario, las "filePaths" se pueden renderizar, pero deseo establecer las "filePaths" en la variable "enlaces".
¿Cuál espero que sea el resultado?
Espero que la variable "enlaces" esté bien en el componente secundario, pudiendo usarse dentro del componente secundario.
¿Cuál es el resultado real?
Al iniciar la aplicación, TypeError: Cannot read property '0' of undefined.
¿Cuál creo que podría ser el problema?
Creo que el componente secundario se procesa sin que el componente principal finalice useEffect() . Me pregunto si hay una manera de decirle al componente secundario que espere a que finalice el componente principal, luego proceda a configurar la variable de "enlaces".
filePaths no estará undefined porque llama a useState() con una entrada vacía.
Hay dos opciones (puedes elegir una) para solucionar esto:
Inicialice filePaths dentro de useState()
Devuelve el componente filePaths Child es nulo/indefinido.
export default function Parent() { const [filePaths, setFilePaths] = useState(); useEffect(() => { var fileContent = JSON.parse(fs.readFileSync("./config.json"); // Reading from a JSON. var tempFilePaths = []; fileContent.FilePaths.forEach((file) => { tempFilePaths.push(file); }); setFilePaths(tempFilePaths); // Contents of "config.js" is now in the "useState". }, []); return ( // return the Child component if the filePaths is not null/undefined {filePaths && <Child filePaths={filePaths}/>} ) } Personalmente, prefiero el segundo porque podemos agregar un componente de carga cuando filePaths aún es nulo/indefinido.
Tiene razón, es por eso que debe cambiar su componente secundario. Representa los filePaths , ya sea que esté definido o no.
Intenta hacer lo siguiente.
export default function Child({filePaths}) { const [links, setLinks] = useState(filePaths); useEffect(()=>{ setLinks(filePaths); },[filePaths]) return ( <div>Nothing here yet, but I would map those links to front-end links.</div> ) }Creo que tienes razón en tu conjetura sobre la secuencia de métodos que llaman:
De acuerdo con esto , cuando usa useEffect, el método se llama después de la representación, como si fuera un método de ciclo de vida de componenteDidMount, que es compatible con el diagrama de ciclo de vida oficial de React y la documentación de React. Y esa es la razón por la que props.filePaths dentro del componente Child no está definido.
Para evitar esto, debe intentar establecer un valor inicial (en el método useState).
algo como lo siguiente (quizás extrayendo la repetición como una función):
// Parent. export default function Parent() { var fileContent = JSON.parse(fs.readFileSync("./config.json"); // Reading from a JSON. var tempFilePaths = []; fileContent.FilePaths.forEach((file) => { tempFilePaths.push(file); }); const [filePaths, setFilePaths] = useState(tempFilePaths); useEffect(() => { var fileContent = JSON.parse(fs.readFileSync("./config.json"); // Reading from a JSON. var tempFilePaths = []; fileContent.FilePaths.forEach((file) => { tempFilePaths.push(file); }); setFilePaths(tempFilePaths); // Contents of "config.js" is now in the "useState". }, []); return ( <Child filePaths={filePaths}/> ) }