问题
i am fetchin details from database wanted to display that into the table, but for initial purpose i wanted to just display on browser without table and stuff.. am getting values.map is not a function but i could the see values printed in console
here iam using function component
export default function SimpleTable() {
const [values, setValues] = useState({});
here is the fetch function
async function handleTable(){
const res = await fetch("http://localhost:4000/productslist")
const data = await res.json()
setValues(data.data)
console.log(data.data)
}
calling the fetch function on useEffect
useEffect(()=>{
handleTable()
},[])
Rendering the values into browser
return (
<div>
{console.log(values)}
{values.map(v => {
return <h4 key={v.idaddproducts}>{v.productName}{v.productId}{v.productBrand}</h4>})}
</div>
);
}
here is the error
Uncaught TypeError: values.map is not a function
回答1:
The initial state of your values is an empty object
From
const [values, setValues] = useState({});
Update to
const [values, setValues] = useState([]);
Since Object doesn't have a method called .map
Also in your code since its a async call you can check based on a state whether data has load or not a simple thing you can add is a ternary check
{values.length && values.map(v => {
return <h4 key={v.idaddproducts}>{v.productName}{v.productId}{v.productBrand}</h4>})}
</div>
);
so once the array has a length greater than zero only it will execute the map function
Working Codesandbox With Sample Example
回答2:
Define your state as an array
const [values, setValues] = useState([]);
Code
{values && values.map(v => {
return <h4 key={v.idaddproducts}>
{v.productName}{v.productId}{v.productBrand}
</h4>
})
}
回答3:
You set a value {}
instead of []
.
Update
const [values, setValues] = useState({});
to
const [values, setValues] = useState([]);
来源:https://stackoverflow.com/questions/59607803/values-map-is-not-a-function-reactjs