Estoy tratando de obtener la identificación del producto de la url usando match.params.id para pasar a la llamada api, pero está dando un error, la coincidencia devuelve indefinida es use match?.params?.id
Cannot read property 'params' of undefinedAplicación.js
<Router> <Switch> <Route path={process.env.PUBLIC_URL +"/images/upload/:id"}> <UploadImages /> </Route> </Switch> </Router>Redirigir:
//params.id from material-ui datagrid table <LinkContainer to={`/admin-panel/home/images/upload/${params.id}`}> <button className="btn btn-primary mr-2">Set Images</button> </LinkContainer> const columns = [ { field: '_id', headerName: 'ID', width: 250 }, { field: 'name', headerName: 'Product Name', width: 300 }, { field: 'price', headerName: 'Price', width: 130 }, { field: 'countInStock', headerName: 'Count In Stock', width: 230 }, { field: 'createdAt', headerName: 'Date Created', width: 230 }, { field: 'action', headerName: 'Action', width: 350, renderCell: (params)=>{ return ( <div> <LinkContainer to={`/admin-panel/home/product/${params.id}/edit`}> <button className="btn btn-info mr-2">Edit</button> </LinkContainer> <LinkContainer to={`/images/upload/${params.id}`}> <button className="btn btn-primary mr-2">Set Images</button> </LinkContainer> <Button className="btn btn-danger" onClick={()=>deleteHandler(params.id)} ><Delete /></Button> </div> ) } }, ]; return ( <div className="productList" style={{height:600}} > {loading ? (<Loader />) : error ? (<Message variant="danger" >{error}</Message>):( <DataGrid rows={products} columns={columns} pageSize={10} rowsPerPageOptions={[5]} checkboxSelection /> )} </div> )}
Cargar imágenes.js
function UploadImages({ location, match, history }) { const productID = match.params.id return (<div></div>); }; export default UploadImagesEl ID se pasa en la URL
http://localhost:3000/images/upload/61555780c208142757be70v1Inicialmente, cuando se carga el componente, los params no están indefinidos. Por favor hacer esto...
const productID = match && match.params && match.params.id; Lo que estás haciendo arriba es esto:
Le está diciendo a reactjs que solo asigne un valor a productID después de realizar las comprobaciones de cordura en el lado derecho.
Una pista de este error:
Cannot read property 'params' of undefined Le dice que está intentando elegir una key llamada param de una variable undefined (en este caso match ).
Entonces, la verificación de cordura anterior significa que le está diciendo a reactjs que solo intente elegir el param si se define la match ; y solo intente elegir id si se define param .
Escribir match?.params?.id es la solución más rápida