我一直在嘗試在收到數(shù)據(jù)并將其設(shè)置為狀態(tài)(使用 useState)后更新函數(shù)。之后該函數(shù)將使用 .map 函數(shù)將數(shù)據(jù)顯示到模板中。但是我遇到兩個錯誤,一個是“projects.map is not a function”(順便說一句,projects 是我的狀態(tài)名稱,存儲數(shù)據(jù)的位置)以及在項(xiàng)目更改時更新的 useEffect 函數(shù)內(nèi)部“預(yù)期分配或函數(shù)調(diào)用和而是看到了一個表情'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
如何使用 useEffect 更新函數(shù)(如 componentDidUpdate)并使用 .map
阿晨1998
2021-08-20 17:31:26