为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用 useEffect 更新函数(如 componentDidUpdate)并使用 .map

如何使用 useEffect 更新函数(如 componentDidUpdate)并使用 .map

阿晨1998 2021-08-20 17:31:26
我一直在尝试在收到数据并将其设置为状态(使用 useState)后更新函数。之后该函数将使用 .map 函数将数据显示到模板中。但是我遇到两个错误,一个是“projects.map is not a function”(顺便说一句,projects 是我的状态名称,存储数据的位置)以及在项目更改时更新的 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
查看完整描述

3 回答

?
慕仙森

TA贡献1827条经验 获得超8个赞

Array.prototype.map() 用于数组。

const [projects, setProjects] = useState('');

项目不是数组。


查看完整回答
反对 回复 2021-08-20
  • 3 回答
  • 0 关注
  • 457 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号