Quiero representar el código de reacción cuando la identificación en los parámetros coincida con la identificación en los datos, pero aquí reaccionar intenta representar el código incluso antes de que se ejecute props.match.params.id , por lo que solo se puede ejecutar la instrucción if. yo con una solución para resolver esto. Incluso he intentado usar useParams() pero no hace nada bueno.
import data from'./data' import React from 'react' export default function Productdisplay(props) { const y= props.match.params.id const product=data.products.find((x) => x.id===y); //An error lies here if(!product){ return( <div>No product to display {}</div> ) } return( <> //Here lies the code I want to render when the ids of the url and data match but as React tries to render the code even before the params is being fetched only if statement is being rendered can you give me a solution for this </> ) }Lo que quiere usar aquí es un useEffect que contiene sus condiciones/lógica que se ejecutará cuando cambien sus deficiencias. Aquí está Y. Luego almacene la salida de su lógica de useEffect en un estado real (useState) y no en una const. A partir de ahí, podrá activar el renderizado que espera.
import React, { useState, useEffect } from 'react'; function Productdisplay(props) { const [products, setProducts] = useState(); useEffect(() => { const y = props ? .match ? .params ? .id; const findProducts = data.products.find((x) => x.id === y); if (findProducts !== products) { setProducts(products); } }, [data?.products, props?.match?.params?.id]); if(!products) return null; return ( <div> // ... </div> );Te sugiero que leas esto https://reactjs.org/docs/hooks-effect.html