我正在获取对象列表。 使用地图功能应该显示一个列表,但没有。我检查了它是否通过 console.log(posts) 保存到“useState”,是的,有一个对象列表。我唯一的问题是我无法将其显示到浏览器。另外,我已经附加了“react”、“reactDOM”和“babel”所需的脚本。
{% extends "network/layout.html" %} {% block body %}
<div id="index"></div>
<script type="text/babel">
const AllPosts = () => {
const [posts, setPosts] = React.useState([]);
React.useEffect(() => {
fetch("/allposts")
.then((response) => response.json())
.then((data) => {
setPosts(data.posts);
})
.catch((error) => {
console.error(error);
});
}, []);
return (
<ul>
{posts &&
posts.map((post, index) => {
<li key={index}>{`Try ${index}`}</li>;
})}
</ul>
);
};
const Index = () => {
return <AllPosts />;
};
const container = document.getElementById("index");
const root = ReactDOM.createRoot(container);
root.render(<Index />);
</script>
{% endblock %}
我想在 li 标签中返回列表中的每个对象,但是,当我在浏览器上检查它时,没有数据。
我认为你重复了
index
两次,而应该是post
。
return (
<ul>
{posts &&
posts.map((post, index) => {
<li key={index}>{`Try ${post}`}</li>;
})}
</ul>