【发布时间】:2019-12-02 19:21:06
【问题描述】:
一旦收到数据并将其设置为状态(使用 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
【问题讨论】:
-
postList函数不返回任何内容。第二个useEffect看起来没有必要。在返回的 JSX 中内联映射就足够了。 -
你可以查看我的答案。与@EmileBergeron 提到的非常相似
标签: javascript reactjs react-hooks