useEffect 和 useState 和 API

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

useEffect and useState and API

问题

I will provide translations for the code and text portions you provided:

// I'm obtaining this data from the backend (successfully) and want to display it, first the names (chatName) in the divs. I don't know where the problem is but the said error run over and over??
// THE ERROR

// Error messages

运行时错误:
×
错误
setChats 不是一个函数
类型错误:setChats 不是一个函数
在 fetchData (http://localhost:3000/main.528b87f895a6cd643323.hot-update.js:37:5)

错误
setChats 不是一个函数
类型错误:setChats 不是一个函数
在 fetchData (http://localhost:3000/main.528b87f895a6cd643323.hot-update.js:37:5)

// MY CODE

import React, { useEffect, useState } from "react";
import axios from "axios";

const Chats = () => {
const { chats, setChats } = useState([]);
const fetchData = async () => {
const { data } = await axios.get("/api/chats");

// console.log(data) consoles the data

setChats(data);

};

useEffect(() => {
fetchData();
});
return (
<>
{typeof chats !== "undefined" ? (

{chats.map((d) => (

{d.chatName}

))}

) : (

Loading...

)}
</>
);
};

export default Chats;

// I want to sort the data in the array using map() or forEach() functions but they are either undefined or setChats is not a function.
// Help display the data once the page is rendered for the first time...thank you,
// API data

// API data

0:
{isGroupChat: false, users: Array(2), _id: '617a077e18c25468bc7c4dd4', chatName: 'John Doe'}
1:
{isGroupChat: false, users: Array(2), _id: '617a077e18c25468b27c4dd4', chatName: 'Guest User'}
2:
{isGroupChat: false, users: Array(2), _id: '617a077e18c2d468bc7c4dd4', chatName: 'Anthony'}
3:
{isGroupChat: true, users: Array(3), _id: '617a518c4081150716472c78', chatName: 'Friends', groupAdmin: {...}}
4:
{isGroupChat: false, users: Array(2), _id: '617a077e18c25468bc7cfdd4', chatName: 'Jane Doe'}
5:
{isGroupChat: true, users: Array(3), _id: '617a518c4081150016472c78', chatName: 'Chill Zone', groupAdmin: {...}}

Please let me know if you need any further assistance or translations.

英文:

I'm obtaining this data from the backend (successfully) and want to display it, first the names (chatName) in the divs. I don't know where the problem is but the said error run over and over??
THE ERROR

Uncaught runtime errors:
&#215;
ERROR
setChats is not a function
TypeError: setChats is not a function
    at fetchData (http://localhost:3000/main.528b87f895a6cd643323.hot-update.js:37:5)
ERROR
setChats is not a function
TypeError: setChats is not a function
    at fetchData (http://localhost:3000/main.528b87f895a6cd643323.hot-update.js:37:5)

MY CODE

import React, { useEffect, useState } from &quot;react&quot;;
import axios from &quot;axios&quot;;
const Chats = () =&gt; {
  const { chats, setChats } = useState([]);
  const fetchData = async () =&gt; {
    const { data } = await axios.get(&quot;/api/chats&quot;);

//console.log(data) consoles the data

    setChats(data);
  };

  useEffect(() =&gt; {
    fetchData();
  });
  return (
    &lt;&gt;
      {typeof chats !== &quot;undefined&quot; ? (
        &lt;div&gt;
          {chats.map((d) =&gt; (
            &lt;div key={d}&gt;{d.chatName}&lt;/div&gt;
          ))}
        &lt;/div&gt;
      ) : (
        &lt;div&gt;Loading...&lt;/div&gt;
      )}
    &lt;/&gt;
  );
};

export default Chats;

I want to sort the data in the array using map() or forEach() funtions but they are either undefined or setChats is not a function.
Help display the data once the page is rendered for the first time...thank you,
API data

0
: 
{isGroupChat: false, users: Array(2), _id: &#39;617a077e18c25468bc7c4dd4&#39;, chatName: &#39;John Doe&#39;}
1
: 
{isGroupChat: false, users: Array(2), _id: &#39;617a077e18c25468b27c4dd4&#39;, chatName: &#39;Guest User&#39;}
2
: 
{isGroupChat: false, users: Array(2), _id: &#39;617a077e18c2d468bc7c4dd4&#39;, chatName: &#39;Anthony&#39;}
3
: 
{isGroupChat: true, users: Array(3), _id: &#39;617a518c4081150716472c78&#39;, chatName: &#39;Friends&#39;, groupAdmin: {…}}
4
: 
{isGroupChat: false, users: Array(2), _id: &#39;617a077e18c25468bc7cfdd4&#39;, chatName: &#39;Jane Doe&#39;}
5
: 
{isGroupChat: true, users: Array(3), _id: &#39;617a518c4081150016472c78&#39;, chatName: &#39;Chill Zone&#39;, groupAdmin: {…}}

答案1

得分: 1

React 的 useState 函数返回一个数组而不是对象,所以在解构赋值中,你需要使用 [ ] 而不是 { }

看看你的 useState

const { chats, setChats } = useState([]);

请将它改为:

const [chats, setChats] = useState([]);

更新:

我还看到你在 useEffect 中获取数据。如果你希望在组件挂载时只调用一次 fetch 函数,我建议你将一个空数组作为 useEffect 函数的第二个参数。否则,它会在每次重新渲染时获取数据。

useEffect(() => {
  fetchData();
}, []);
英文:

React useState function returns an array not an object, so you have to use [ ] instead of { } in destructuring assignment

Look at your useState:

const { chats, setChats } = useState([]);

and change it to

const [chats, setChats] = useState([]);

UPD:

I also see you fetch data in useEffect. I recommend you to add an empty array as a second parameter of useEffect function if you want to call fetch function only once when component mounted. Otherwise it will fetch data on every re-render.

useEffect(() =&gt; {
  fetchData();
}, []);

huangapple
  • 本文由 发表于 2023年5月10日 15:48:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76216069.html
匿名

发表评论

匿名网友

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

确定