页面显示“没有可用数据”,尽管我在React中获取到了用户列表。

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

Page says 'No data available' even though I am getting user lists in react

问题

问题:

当我在登陆页面点击“查看用户”按钮时,它会将我带到查看页面,我想要在那里呈现用户列表。但是它显示“无可用数据”。

代码:

登陆页面:

  1. import React, { useState, useEffect } from 'react';
  2. import axios from 'axios';
  3. import '../../src/App.css';
  4. import { Button } from '@mui/material';
  5. import { useNavigate } from 'react-router-dom';
  6. const LandingPage = () => {
  7. const [alertShown, setAlertShown] = useState(false);
  8. useEffect(() => {
  9. if (!alertShown) {
  10. alert("You've successfully logged in!");
  11. setAlertShown(true);
  12. }
  13. }, [alertShown]);
  14. const navigate = useNavigate();
  15. const handleRedirectToView = () => {
  16. navigate('/view');
  17. };
  18. return (
  19. <div
  20. style={{
  21. backgroundImage: 'url("https://milonelawoffice.com/wp-content/uploads/2016/08/slide3.jpg")',
  22. width: 1280,
  23. height: 609,
  24. backgroundSize: 'cover',
  25. backgroundRepeat: 'no-repeat',
  26. paddingTop: 80
  27. }}
  28. >
  29. <headingText style={{ fontSize: "40px", textAlign: "center" }}>Welcome to the Dashboard!</headingText>
  30. <br></br>
  31. <center>
  32. <Button onClick={handleRedirectToView} variant="contained" sx={{ backgroundColor: '#C1C8EB', color: '#0C142C' }}>View Users</Button>
  33. </center>
  34. </div>
  35. );
  36. };
  37. export default LandingPage;

查看页面:

  1. import React, { useState, useEffect } from 'react';
  2. import '../../src/App.css';
  3. const View = () => {
  4. const [data, setData] = useState([]);
  5. useEffect(() => {
  6. fetch("http://localhost:4000/getUser", {
  7. method: "GET",
  8. })
  9. .then((res) => res.json())
  10. .then((data) => {
  11. setData(data.data);
  12. });
  13. },[]);
  14. return(
  15. <div>
  16. {data && data.length > 0 ? (
  17. <table>
  18. <thead>
  19. <tr>
  20. <th>Email</th>
  21. <th>Password</th>
  22. </tr>
  23. </thead>
  24. <tbody>
  25. {data.map(i => (
  26. <tr key={i.email}>
  27. <td>{i.email}</td>
  28. <td>{i.password}</td>
  29. </tr>
  30. ))}
  31. </tbody>
  32. </table>
  33. ) : (
  34. <p>No data available</p>
  35. )}
  36. </div>
  37. )
  38. };
  39. export default View;

我尝试获取用户列表。

我期望它在屏幕上呈现。

但是我得到的只是在浏览器控制台中显示为JSON数组的用户列表。

英文:

I am a beginner in MERN stack. I am just stuck at one place and it has been hours I cant solve it.

Issue:

When I press view users button in landing page, it takes me to view page where I want to render user lists. But it says No data available.
Error

CODE:

Landing Page:

  1. import React, { useState, useEffect } from &#39;react&#39;;
  2. import axios from &#39;axios&#39;;
  3. import &#39;../../src/App.css&#39;;
  4. import { Button } from &#39;@mui/material&#39;;
  5. import { useNavigate } from &#39;react-router-dom&#39;;
  6. const LandingPage = () =&gt; {
  7. const [alertShown, setAlertShown] = useState(false);
  8. useEffect(() =&gt; {
  9. if (!alertShown) {
  10. alert(&quot;You&#39;ve successfully logged in!&quot;);
  11. setAlertShown(true);
  12. }
  13. }, [alertShown]);
  14. const navigate = useNavigate();
  15. const handleRedirectToView = () =&gt; {
  16. navigate(&#39;/view&#39;);
  17. };
  18. return (
  19. &lt;div
  20. style={{
  21. backgroundImage: &#39;url(&quot;https://milonelawoffice.com/wp-content/uploads/2016/08/slide3.jpg&quot;)&#39;,
  22. width: 1280,
  23. height: 609,
  24. backgroundSize: &#39;cover&#39;,
  25. backgroundRepeat: &#39;no-repeat&#39;,
  26. paddingTop: 80
  27. }}
  28. &gt;
  29. &lt;headingText style={{ fontSize: &quot;40px&quot;, textAlign: &quot;center&quot; }}&gt;Welcome to the Dashboard!&lt;/headingText&gt;
  30. &lt;br&gt;&lt;/br&gt;
  31. &lt;center&gt;
  32. &lt;Button onClick={handleRedirectToView} variant=&quot;contained&quot; sx={{ backgroundColor: &#39;#C1C8EB&#39;, color: &#39;#0C142C&#39; }}&gt;View Users&lt;/Button&gt;
  33. &lt;/center&gt;
  34. &lt;/div&gt;
  35. );
  36. };
  37. export default LandingPage;

View page:

  1. import React, { useState, useEffect } from &#39;react&#39;;
  2. import &#39;../../src/App.css&#39;;
  3. const View = () =&gt; {
  4. const [data, setData] = useState([]);
  5. useEffect(() =&gt; {
  6. fetch(&quot;http://localhost:4000/getUser&quot;, {
  7. method: &quot;GET&quot;,
  8. })
  9. .then((res) =&gt; res.json())
  10. .then((data) =&gt; {
  11. setData(data.data);
  12. });
  13. },[]);
  14. return(
  15. &lt;div&gt;
  16. {data &amp;&amp; data.length &gt; 0 ? (
  17. &lt;table&gt;
  18. &lt;thead&gt;
  19. &lt;tr&gt;
  20. &lt;th&gt;Email&lt;/th&gt;
  21. &lt;th&gt;Password&lt;/th&gt;
  22. &lt;/tr&gt;
  23. &lt;/thead&gt;
  24. &lt;tbody&gt;
  25. {data.map(i =&gt; (
  26. &lt;tr key={i.email}&gt;
  27. &lt;td&gt;{i.email}&lt;/td&gt;
  28. &lt;td&gt;{i.password}&lt;/td&gt;
  29. &lt;/tr&gt;
  30. ))}
  31. &lt;/tbody&gt;
  32. &lt;/table&gt;
  33. ) : (
  34. &lt;p&gt;No data available&lt;/p&gt;
  35. )}
  36. &lt;/div&gt;
  37. )
  38. };
  39. export default View;

I tried to get list of users.

I was expecting it to be rendered on screen.

But all I got was lists of users showing as array in JSON inside console of browser.

答案1

得分: 1

尝试控制台输出 data,我认为状态 data 没有正确设置。

  1. useEffect(() => {
  2. fetch("http://localhost:4000/getUser") // 在这种情况下不需要设置方法,因为默认是 Get。
  3. .then((res) => res.json())
  4. .then((data) => {
  5. setData(data); // 仅用户数组
  6. });
  7. }, []);
英文:

Try to console data, i think that the state data is not set properly.

  1. useEffect(() =&gt; {
  2. fetch(&quot;http://localhost:4000/getUser&quot;) //there is no need for setting the method in this case because it&#39;s by default Get.
  3. .then((res) =&gt; res.json())
  4. .then((data) =&gt; {
  5. setData(data); //just the array of users
  6. });
  7. },[]);

答案2

得分: 1

我可以尝试帮助您解答一个问题和提供两个提示:

问题:您确定data.data存在吗? setData(data.data); 如果我没记错的话,应该是这个响应结构:

  1. data: {
  2. data: {}
  3. }

也许这是导致您的代码出现问题的原因。

提示:

  1. 使用 console.log(data) 来检查数据是否被存储在状态中。(应该在return()之前和useEffect之后使用)
  2. 创建一个带有应用 try catch 的fetch方法的辅助文件。
    您可以在这里找到一些示例和更多信息:https://ilikekillnerds.com/2023/02/handling-errors-with-the-fetch-api/
英文:

I can try to help you with one question and two tips:

Q: Are you sure that data.data exists? setData(data.data); This should be the response structure if I'm not wrong:

  1. data: {
  2. data: {}
  3. }

Maybe that's what's breaking your code.

Tips:

  1. Use console.log(data) so you can check if data is being stored on state. (Should be before return() and after useEffect)
  2. Create a helper file with fetch method applying try catch.
    Here you'll find some examples and more information about it.
    <https://ilikekillnerds.com/2023/02/handling-errors-with-the-fetch-api/>

huangapple
  • 本文由 发表于 2023年6月12日 05:25:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76452566.html
匿名

发表评论

匿名网友

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

确定