React:我无法打印获取到的数据。

huangapple go评论82阅读模式
英文:

React: I can't print the data fetched

问题

如我上面所写的,我无法打印从fetch中恢复的数据,我已经花了一些时间但没有任何结果。

我是React的新手,正在学习如何使用hooks。

我得到的错误是:
无法读取未定义的属性(读取'map')

import React, { useEffect, useState } from 'react';
import './App.css';

export default function App() {
  const [users, setUsers] = useState();
  useEffect(async () => {
    await fetch('https://jsonplaceholder.typicode.com/users/').then(response => response.json()).then(data => setUsers(data))
  }, []);

  return (
    <div>
      {
        users.map((user) => {
          <div>{user.name}</div>
        })
      }
    </div>
  )
}

你能帮助我吗?

英文:

As I wrote above, I can't print the data recovered from the fetch, I've been on this for some time without any results.

I'm new to React and learning how to use hooks.

The error I'm getting is:
Cannot read properties of undefined (reading 'map')

import React, { useEffect, useState } from &#39;react&#39;;
import &#39;./App.css&#39;;

export default function App() {
  const [users, setUsers] = useState();
  useEffect(async () =&gt; {
    await fetch(&#39;https://jsonplaceholder.typicode.com/users/&#39;).then(response =&gt; response.json()).then(data =&gt; setUsers(data))
  }, []);

  return (
    &lt;div&gt;
      {
        users.map((user) =&gt; {
          &lt;div&gt;{user.name}&lt;/div&gt;
        })
      }
    &lt;/div&gt;
  )
}

Can you kindly help me?

答案1

得分: 3

  1. 将一个空数组作为默认值添加到useState中,以确保map()始终存在。(第一次渲染将在空数组上进行map操作,这是可以的,因为还没有数据)
    const [users, setUsers] = useState([]);
    
  2. useEffect的回调函数不应该是await/async,将其移除。
  3. 你没有从map()中返回任何内容,我已经将其更改为:
    {
      users.map((user) => {
        return <div>{user.name}</div>
      })
    }
    

    或者使用简写的返回方式:

    {
      users.map(user => <div>{user.name}</div>)
    }
    
const { useState, useEffect } = React;

const App = () => {
  const [users, setUsers] = useState([]);
  useEffect(() => {
      fetch('https://jsonplaceholder.typicode.com/users/')
          .then(response => response.json())
          .then(data => setUsers(data))
  }, []);
  
  return (
    <div>
      {
        users.map((user) => {
          return <div>{user.name}</div>
        })
      }
    </div>
  )
}

ReactDOM.render(<App />, document.getElementById("react"));
html, body { height: 100vh; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>
英文:
  1. Add a default value as empty array to useState to make sure that map() always exist. (The first render will map on an empty array, which is fine since there is not data yet)
    const [users, setUsers] = useState([]);
    
  2. useEffect callback should not be await/async, removed that
  3. You didn't return anything from your map(), I've changed it to:
    {
      users.map((user) =&gt; {
        return &lt;div&gt;{user.name}&lt;/div&gt;
      })
    }
    

    Or as the short-hand return style:

    {
      users.map(user =&gt; &lt;div&gt;{user.name}&lt;/div&gt;)
    }
    
    • <https://stackoverflow.com/questions/39999671/map-function-not-working-in-react>
    • <https://stackoverflow.com/questions/70361452/react-js-map-is-not-rendering-components>

<!-- begin snippet: js hide: false console: true babel: true -->

<!-- language: lang-js -->

const { useState, useEffect } = React;

const App = () =&gt; {
  const [users, setUsers] = useState([]);
  useEffect(() =&gt; {
      fetch(&#39;https://jsonplaceholder.typicode.com/users/&#39;)
          .then(response =&gt; response.json())
          .then(data =&gt; setUsers(data))
  }, []);
  
  return (
    &lt;div&gt;
      {
        users.map((user) =&gt; {
          return &lt;div&gt;{user.name}&lt;/div&gt;
        })
      }
    &lt;/div&gt;
  )
}

ReactDOM.render(&lt;App /&gt;, document.getElementById(&quot;react&quot;));

<!-- language: lang-css -->

html, body { height: 100vh; }

<!-- language: lang-html -->

&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js&quot;&gt;&lt;/script&gt;
&lt;div id=&quot;react&quot;&gt;&lt;/div&gt;

<!-- end snippet -->

答案2

得分: 0

问题在于在开始时usersundefined,你有两种方法可以解决这个问题:

  1. 将一个空数组设置为users的默认值:useState([])
const [users, setUsers] = useState([]);
  1. usersundefined时,显示其他内容,比如加载文本
import React, { useEffect, useState } from 'react';
import './App.css';

export default function App() {
  const [users, setUsers] = useState();
  useEffect(async () => {
    await fetch('https://jsonplaceholder.typicode.com/users/').then(response => response.json()).then(data => setUsers(data))
  }, []);

  return (
    <div>
      {!users && "loading users..."}
      {
        users && users.map((user) => {
          <div>{user.name}</div>
        })
      }
    </div>
  )
}
英文:

The issue is that users is undefined at the start, you have 2 ways to solve this:

  1. set an empty array as default for users: useState([])
const [users, setUsers] = useState([]);
  1. show something else like a loading text when users is undefined
import React, { useEffect, useState } from &#39;react&#39;;
import &#39;./App.css&#39;;

export default function App() {
  const [users, setUsers] = useState();
  useEffect(async () =&gt; {
    await fetch(&#39;https://jsonplaceholder.typicode.com/users/&#39;).then(response =&gt; response.json()).then(data =&gt; setUsers(data))
  }, []);

  return (
    &lt;div&gt;
      {!users &amp;&amp; &quot;loading users...&quot;}
      {
        users &amp;&amp; users.map((user) =&gt; {
          &lt;div&gt;{user.name}&lt;/div&gt;
        })
      }
    &lt;/div&gt;
  )
}

huangapple
  • 本文由 发表于 2023年8月8日 23:07:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76860861.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定