【问题标题】:How to update a function with useEffect (like componentDidUpdate) and use .map function to display from JSON file ReactJS如何使用 useEffect 更新函数(如 componentDidUpdate)并使用 .map 函数从 JSON 文件 ReactJS 显示
【发布时间】: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


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

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

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

    项目不是数组。

    【讨论】:

      【解决方案3】:

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

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

      ,因为目前projects是一个空字符串,没有map函数。

      对于获取,你应该这样写:

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

      希望这会有所帮助。

      【讨论】:

      • 谢谢,数据接收正常,只是useEffect中的回调函数'postList'不起作用。
      • 您希望准确地调用 useEffect 的时间和频率?
      • 应该调用一次,就是接收到数据的时候
      • 您应该将整个 projects.map 移动到组件的渲染/返回中。这样您就不必跟踪 postList。这样,只有您的 useState 中的项目才是事实的来源。如果你真的想使用 postList 对象(不推荐),你必须像这样返回它:return projects.map(...);
      【解决方案4】:

      试试这个

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

      .then(data => setProjects(data))
      

      假设数据是一个数组

      【讨论】:

      • 我被困在“预期分配或函数调用,而是看到一个表达式”,如果我删除调用“postList”函数的 useEffect,它会说 .length 不是函数,在三元运算符中。但是我希望功能在状态改变后重新加载
      猜你喜欢
      • 2020-11-22
      • 2019-06-16
      • 1970-01-01
      • 1970-01-01
      • 2021-11-09
      • 2020-11-16
      • 1970-01-01
      • 1970-01-01
      • 2017-11-14
      相关资源
      最近更新 更多