javascript - 为什么我不能映射这个数组
问题描述
你能帮我弄清楚为什么我不能映射这个数组。下面是错误和我正在运行的代码:
TypeError: posts.map is not a function
这是我的代码导致上述错误:
import React from 'react';
import {useEffect, useState} from 'react';
import { Container, Row, Col } from 'bootstrap-4-react';
export default function Post() {
//posts array to be mapped
const [posts, setPosts] = useState([{
title: "",
postContent: ""
}]);
useEffect(() => {
//fetches a GET route
fetch(`${process.env.REACT_APP_SERVER_URL}/posts/:id`).then(res => {
if (res.ok) {
return res.json()
}
}).then(jsonRes => setPosts(jsonRes));
})
return (
<div>
<h1>Hello</h1>
//cant seem to be able to map this array
{posts.map(post => {
<>
<h1>{post.title}</h1>
<p>{post.postContent}</p>
</>
})}
</div>
)}
解决方案
You need to wrap the mapped returned code block within parenthesis ()
and not in curly brackets {}
in order to return the html correctly
//...
return (
<div>
<h1>Hello</h1>
{posts.map(post => (
<>
<h1>{post.title}</h1>
<p>{post.postContent}</p>
</>
))}
</div>
)
}
Edit:
Also, I suggest adding an empty dependency array as the second argument for your useEffect(() => { //your code }, [])
This will make it so your component doesn't re-render sporadically and end up fetching your data a ridiculous amount of times.
推荐阅读
- android - 创建首选项屏幕时找不到androidx.preference.PreferenceScreen
- asp.net-mvc - ASP.Net MVC 动态输入绑定到相同的控制器属性
- prolog - 如何在prolog中进行递归?
- angular - 调试从 Angular CLI 的 `ng e2e` 开始的量角器测试
- javascript - 有可能attributeChangedCallback 得到一个像newVal 这样的对象吗?
- querydsl - 在 Querydsl 中 - 是否可以使用 java 集合加入实体
- javascript - 如果 url 等于链接的 href,则添加一个类
- r - 使用 ggplot2 创建一个闪避的条形图
- c# - 使用 OData 客户端 v3 扩展嵌套对象
- c++ - 为 MyString 类设置 reverse_iterator::rbegin() 和 reverse_iterator::rend()