如何使用 useEffect(如 componentDidUpdate)更新函数并使用 .map 函数显示 JSON 文件 ReactJS

How to update a function with useEffect (like componentDidUpdate) and use .map function to display from JSON file ReactJS

我一直在尝试在接收到数据并将其设置为状态(使用 useState)后更新函数。之后该函数将使用 .map 函数将数据显示到模板中。

但是我遇到了两个错误,一个是 'projects.map is not a function'(顺便说一句,projects 是我的州名称,数据存储在其中),另一个是 useEffect 函数,该函数在项目更改时更新 'Expected an assignment or function call and instead saw an expression'

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

试试这个

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

.then(data => setProjects(data))

假设数据是一个数组

首先,您必须将初始项目设置为空数组,如下所示:

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

,因为目前projects是一个空字符串,没有map功能

对于fetch,应该这样写:

 useEffect(async () => {
     const data = await fetch('https://jsonplaceholder.typicode.com/posts')
       .then(response => response.json())
     setProjects(data);
}, []);

希望对您有所帮助。

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

const [项目,setProjects] = useState('');

投影不是数组。

您需要对您的组件进行一些更正

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

您可能想要添加额外的检查以确定帖子何时加载以及加载完成后它们何时为空,这样您就不会只收到加载消息