i have a mini tp that i want to map a array of objects , and i find a problem of the function map didn't working , in this tp i have the function App()
use the function Ptot()
that map a array of objects with the function Prot()
the problem: `
Uncaught TypeError: data.map is not a function
at Ptot (Ptot.js:9:1)
at renderWithHooks (react-dom.development.js:16305:1)
at mountIndeterminateComponent (react-dom.development.js:20074:1)
at beginWork (react-dom.development.js:21587:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1)
at invokeGuardedCallback (react-dom.development.js:4277:1)
at beginWork$1 (react-dom.development.js:27451:1)
at performUnitOfWork (react-dom.development.js:26557:1)
at workLoopSync (react-dom.development.js:26466:1)
`
App.js:
import React from "react";
import Ptot from "./Ptot";
const Produits=[
{
id:1,
title:"pc pourtable hp",
prix:'7490',
image:""
},
{
id:2,
title:"pc pourtable delet",
prix:'8990',
image:""
},
{
id:1,
title:"pc pourtable infnx",
prix:'6590',
image:""
}
];
function App(){
return(
<div>
hello
<Ptot props={Produits} />
</div>
)
}
export default App;
Prot.js:
import React from "react";
function Prot(element) {
return (
<div>
<p>hello</p>
<div>
<div className="col">
<div className="cart-shadow-sm">
<img className="bd-placeholder-img card-img-top" src={`image/${element.image}`} alt="" />
<div className="card-body">
<p className="card-title">{element.title}</p>
<p className="card-text">{element.prix}</p>
<div className="d-flex justify-conten-between align-items-center">
<div className="btn-group">
<button type="button" className="btn btn-sm btn-outline-secondary">Ajoute un paner</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
)
}
export default Prot;
Ptot.js:
import React from "react";
import Prot from './Prot.js'
import { useState } from "react";
function Ptot(props){
const [data,setData]=useState(props)
return (
<div className="container">
<div >
{
data.map((elm)=>{
<Prot element={elm} />
})
}
</div>
</div>
)
}
export default Ptot;
CodePudding user response:
A component's props
is an object. Don't call a props
property props
, call it something else like data
:
<Ptot data={Produits} />
and then destructure data
from the component props object, and map
over that instead.
function Ptot({ data }) { ... }
CodePudding user response:
When you render a React component, all the props get passed into the component function as a single argument (most often called props
).
So when you have this
<Ptot props={Produits} />
Inside your Ptot
function, it’s actually passed in like this
function Ptot (props) {
console.log(props);
// { props: […] }
console.log(props.props);
// [{ id: 1, …}, …]
}
So what you want is something like this instead
<Ptot data={Produits} />
function Ptot(props) {
return props.data.map(elm => (…));
}
CodePudding user response:
Try to get the props in Ptot.js
as object field
.
.
function Ptot({props}){
.
.