Estoy tratando de mapear sobre una matriz en State y mostrar los valores del objeto para el título, pero sigo obteniendo [object object] .
El siguiente código solo devuelve los valores del título cuando se muestra como un archivo console.log. No estoy seguro de lo que me estoy perdiendo, ¡pero agradecería cualquier consejo!
// State const [cart, setCart] = useState({ wasteContents: [] }); // Set State setAnswers(prevAnswers => { const wasteContents = prevAnswers.wasteContents; const alreadyExists = wasteContents.find(item => item.title === title) !== undefined; if (!alreadyExists) { wasteContents.push({ title, quantity: 0, }); } return { ...prevAnswers, wasteContents: wasteContents.map(item => { if (item.title === title) { return { ...item, quantity, }; } return item; }), }; }); // Map cart.wasteContents.map(items => { return items.title; // [object object] // return console.log(); // prints value of 'title' }); // Data saved in state State : {wasteContents: Array(3), wasteQuantity: "Singular …} wasteQuantity : "Singular Item(s)" wasteQuantityWeight : undefined wasteContents : [{…}, {…}, {…}] 0 : {quantity: 2, title: "Household Junk"} 1 : {quantity: 1, title: "Furniture"} 2 : {quantity: 1, title: "Appliances"}Su función con su entrada funciona bien como se esperaba
let wasteContents = [{title: 'Household Junk', quantity: 1}, {title: '33Household Junk', quantity: 1}, {title: '22Household Junk', quantity: 1}] const test = () => wasteContents.map(items => { console.log(items) return items.title; }); test();Veo la etiqueta de reacción en su componente, así que supongo que está usando esto para representar algunos componentes. Deberías actualizar de esta manera.
{cart.wasteContents.map(items => return ( <p>{items.title}</p> ) )}Entonces, al final, conseguí que esto funcionara usando return cart.wasteContents.map((item) => { return item.title; }); ! ¡La razón por la que la respuesta anterior no funcionó se debió a que se perdió el return de la función de mapa real! 😅