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

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

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

问题

问题:

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

代码:

登陆页面:

import React, { useState, useEffect } from 'react';
import axios from 'axios';
import '../../src/App.css';
import { Button } from '@mui/material';
import { useNavigate } from 'react-router-dom';

const LandingPage = () => {
    const [alertShown, setAlertShown] = useState(false);

    useEffect(() => {
        if (!alertShown) {
            alert("You've successfully logged in!");
            setAlertShown(true);
        }
    }, [alertShown]);

    const navigate = useNavigate();

    const handleRedirectToView = () => {
        navigate('/view');
    };

    return (
        <div
            style={{
                backgroundImage: 'url("https://milonelawoffice.com/wp-content/uploads/2016/08/slide3.jpg")',
                width: 1280,
                height: 609,
                backgroundSize: 'cover',
                backgroundRepeat: 'no-repeat',
                paddingTop: 80
            }}
        >
            <headingText style={{ fontSize: "40px", textAlign: "center" }}>Welcome to the Dashboard!</headingText>
            <br></br>
            <center>
                <Button onClick={handleRedirectToView} variant="contained" sx={{ backgroundColor: '#C1C8EB', color: '#0C142C' }}>View Users</Button>
            </center>
        </div>
    );
};

export default LandingPage;

查看页面:

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

const View = () => {
    const [data, setData] = useState([]);

    useEffect(() => {
      fetch("http://localhost:4000/getUser", {
        method: "GET",
      })
      .then((res) => res.json())
      .then((data) => {
        setData(data.data);
      });
    },[]);

    return(
        <div>
            {data && data.length > 0 ? (
                <table>
                    <thead>
                        <tr>
                            <th>Email</th>
                            <th>Password</th>
                        </tr>
                    </thead>
                    <tbody>
                        {data.map(i => (
                            <tr key={i.email}>
                                <td>{i.email}</td>
                                <td>{i.password}</td>
                            </tr>
                        ))}
                    </tbody>
                </table>
            ) : (
                <p>No data available</p>
            )}
        </div>
    )
};

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:

import React, { useState, useEffect } from &#39;react&#39;;
import axios from &#39;axios&#39;;
import &#39;../../src/App.css&#39;;
import { Button } from &#39;@mui/material&#39;;
import { useNavigate } from &#39;react-router-dom&#39;;

const LandingPage = () =&gt; {
    const [alertShown, setAlertShown] = useState(false);

    useEffect(() =&gt; {
        if (!alertShown) {
            alert(&quot;You&#39;ve successfully logged in!&quot;);
            setAlertShown(true);
        }
    }, [alertShown]);


    const navigate = useNavigate();

    const handleRedirectToView = () =&gt; {
        navigate(&#39;/view&#39;);
    };

    return (
        &lt;div
            style={{
                backgroundImage: &#39;url(&quot;https://milonelawoffice.com/wp-content/uploads/2016/08/slide3.jpg&quot;)&#39;,
                width: 1280,
                height: 609,
                backgroundSize: &#39;cover&#39;,
                backgroundRepeat: &#39;no-repeat&#39;,
                paddingTop: 80
            }}
        &gt;
            &lt;headingText style={{ fontSize: &quot;40px&quot;, textAlign: &quot;center&quot; }}&gt;Welcome to the Dashboard!&lt;/headingText&gt;
            &lt;br&gt;&lt;/br&gt;
            &lt;center&gt;
                &lt;Button onClick={handleRedirectToView} variant=&quot;contained&quot; sx={{ backgroundColor: &#39;#C1C8EB&#39;, color: &#39;#0C142C&#39; }}&gt;View Users&lt;/Button&gt;
            &lt;/center&gt;
        &lt;/div&gt;
    );
};

export default LandingPage;

View page:

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

const View = () =&gt; {
    const [data, setData] = useState([]);

    useEffect(() =&gt; {
      fetch(&quot;http://localhost:4000/getUser&quot;, {
        method: &quot;GET&quot;,
      })
      .then((res) =&gt; res.json())
      .then((data) =&gt; {
        setData(data.data);
      });
    },[]);

    return(
        &lt;div&gt;
            {data &amp;&amp; data.length &gt; 0 ? (
                &lt;table&gt;
                    &lt;thead&gt;
                        &lt;tr&gt;
                            &lt;th&gt;Email&lt;/th&gt;
                            &lt;th&gt;Password&lt;/th&gt;
                        &lt;/tr&gt;
                    &lt;/thead&gt;
                    &lt;tbody&gt;
                        {data.map(i =&gt; (
                            &lt;tr key={i.email}&gt;
                                &lt;td&gt;{i.email}&lt;/td&gt;
                                &lt;td&gt;{i.password}&lt;/td&gt;
                            &lt;/tr&gt;
                        ))}
                    &lt;/tbody&gt;
                &lt;/table&gt;
            ) : (
                &lt;p&gt;No data available&lt;/p&gt;
            )}
        &lt;/div&gt;
    )

};

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 没有正确设置。

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

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

useEffect(() =&gt; {
  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.
  .then((res) =&gt; res.json())
  .then((data) =&gt; {
    setData(data); //just the array of users
  });
},[]);

答案2

得分: 1

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

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

data: {
  data: {}
}

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

提示:

  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:

data: {
  data: {}
}

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:

确定