我一直在尝试在收到数据并将其设置为状态(使用 useState(后更新函数。之后,该函数将使用 .map 函数将数据显示到模板中。
但是我收到两个错误,一个是"projects.map 不是一个函数"(顺便说一句,项目是我的州名称,数据存储在哪里(和在 useEffect 函数中,当项目更改时更新"预期赋值或函数调用,而是看到一个表达式">
import React, { useState, useEffect } from 'react';
import ProjectSummary from './projectSummary';
function ProjectList() {
// setting my state
const [projects, setProjects] = useState([])
// getting the data from some dummy online data when the app starts
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(data => setProjects({ data }))
}, []);
// makeing a function call postList, which stores a ternery operator
const postList = () => {
// The ternery operator asks if there is anything inside the porjects state
projects.length ? (
// If there is something in the state, it will map out the JSON array in the 'projectSummary template
projects.map(projects => {
return(
<div >
<ProjectSummary key={projects.id} title={projects.title} author={projects.userId} date='30 september, 2019' content={projects.body}/>
</div>
)
})
) : (
// If there isnt anything in the state is prints out 'Loading Data'
<h1>Loading Data</h1>
);
}
// useEffect updates when the 'projects' stae is updated (like componentDidUpdate, and runs the function again
useEffect(() => {
postList()
}, [projects]);
return(
<div className="ProjectList">
// The component should output the postList function, which should map out the array, in the template
{ postList }
</div>
)
}
export default ProjectList
您需要对组件进行一些更正
import React, { useState, useEffect } from 'react';
import ProjectSummary from './projectSummary';
function ProjectList() {
const [projects, setProjects] = useState([])
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(data => setProjects(data))
}, []);
return(
<div className="ProjectList">
{
projects.length ?
projects.map(projects => (
<div>
<ProjectSummary key={projects.id} title={projects.title} author={projects.userId} date='30 september, 2019' content={projects.body} />
</div>
))
:
<h1>Loading Data</h1>
}
</div>
)
}
export default ProjectList;
您不需要postList
函数和第二个useEffect
。
您可能需要添加其他检查来确定帖子何时加载以及加载完成后何时为空,这样您就不会只收到加载消息
试试这个
const [projects, setProjects] = useState([])
和
.then(data => setProjects(data))
假设数据是一个数组
首先,您必须将初始项目设置为空数组,如下所示:
const [projects, setProjects] = useState([])
,因为当前项目是一个空字符串,它没有 map 函数。
对于获取,您应该这样写:
useEffect(async () => {
const data = await fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
setProjects(data);
}, []);
希望这有帮助。
Array.prototype.map(( 用于 Array。
const [projects, setProjects] = useState(''(;
项目不是数组。