收到错误:"对象作为 React 子对象无效"在数组渲染中



我正在尝试做一项简单的任务。呈现数组的内容:

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>)}
);

注释(resp.data.comments(以对象数组的形式出现:

comments = [{'post': 'something', 'timestamp': 'some time'}]

我得到的错误输出:

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.(但我使用的是一个数组。一个对象数组(

由于resp.data.comments是一个数组,您可以直接设置为使用setComments(resp.data.comments)声明注释,并使用jsx中的Array.prototype.map函数进行渲染。

const [comments, setComments] = useState([]);   // an array to begin with

handleFetch = () => {
...
...
setComments(resp.data.comments);
...
}

return (
<>
{comments.map(comm => <p>{comm.post}</p>)}
</>
);

您需要使用.map()来返回值。所以你可以这样修复:

return (
<>
{comments.map((comm, index) => <p key={index}>{comm.post}</p>)}
</>
);

相关内容

最新更新