I'm trying to do a simple task. Rendering contents of an array:
const [comments, setComments] = useState([]); // an array to begin with
handleFetch = () => {
...
...
const obj = resp.data.comments;
const new_array = new Array();
new_array.push(obj);
setComments(new_array);
...
}
return (
{comments.forEach(comm => <p>{comm.post}</p>)}
);
comments ( resp.data.comments
) come in as an array of objects:
comments = [{'post': 'something', 'timestamp': 'some time'}]
Error output I'm getting:
Error: Objects are not valid as a React child (found: object with keys {post, timestamp}). If you meant to render a collection of children, use an array instead.
(But I'm using an array. An array of objects)
Since resp.data.comments
is an array, you can directly set to it to state comments using setComments(resp.data.comments)
and use Array.prototype.map
function in jsx to render.
const [comments, setComments] = useState([]); // an array to begin with
handleFetch = () => {
...
...
setComments(resp.data.comments);
...
}
return (
<>
{comments.map(comm => <p>{comm.post}</p>)}
</>
);
You need to use .map()
to return the value. So you can fix like this:
return (
<>
{comments.map((comm, index) => <p key={index}>{comm.post}</p>)}
</>
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.