【问题标题】:Why is there an error when refreshing the page? react为什么刷新页面时会出错?反应
【发布时间】:2021-12-14 14:18:37
【问题描述】:

在我登录用户页面后,我尝试刷新页面 - 它抛出错误?

这是我的仪表板,在我的应用程序中已经在运行,它工作正常,但是当我尝试刷新它时已经在用户页面上出现错误

这是我的代码 https://codesandbox.io/s/serene-https-oi6hw

错误是:

错误:对象作为 React 子对象无效(找到:带有键 {} 的对象)。如果您打算渲染一组孩子,请使用 代替数组。

import { useSelector } from "react-redux";
//react-redux actions
import { Userinfo } from "../auth/actions/userActions";
import { logoutUser } from "../auth/actions/userActions";

//history
import { useHistory } from "react-router-dom";


const Dashboard = () => {
  const history = useHistory();
  const selectUser = (state) => state.user;
  const user = useSelector(selectUser);
  

  return (
  <div>
      <div
        style={{
          position: "absolute",
          top: 0,
          left: 0,
          backgroundColor: "transparent",
          width: "100%",
          padding: "15px",
          display: "flex",
          justifyContent: "flex-start"
        }}
      >
        <Avatar image={Logo} />
      </div>
      <StyledFromArea bg={colors.dark2}>
        <StyledTitle size={65}>Hello, {user}</StyledTitle>
        <Userinfo />
        <ButtonGroup>
          <StyledButton to="#" onClick={() => logoutUser(history)}>
            Logout
          </StyledButton>
        </ButtonGroup>
      </StyledFromArea>
    </div>
  );
};
export default Dashboard;

【问题讨论】:

  • 我不认为你的 JSX 标签匹配,你似乎有一个 &lt;/div&gt; 很多

标签: javascript reactjs redux react-redux


【解决方案1】:

问题来了


<StyledTitle size={65}>Hello, {user}</StyledTitle>

用户是一个对象。 试试您好,{user?.email} 或您要显示的属性

【讨论】:

  • 我尝试显示来自我的 reduce 的用户名,我的代码运行良好,直到我尝试重新加载页面,当我刷新页面时它显示错误
  • 尝试 console.log(user) 并在刷新前和刷新后检查用户中的内容
  • 我试了一下,之前有用户信息,但是刷新后信息是空的
  • 使用“redux-persist”库持久化用户
【解决方案2】:

试试这个:

import { useSelector } from "react-redux";
//react-redux actions
import { Userinfo } from "../auth/actions/userActions";
import { logoutUser } from "../auth/actions/userActions";

//history
import { useHistory } from "react-router-dom";


const Dashboard = () => {
  const history = useHistory();
  const selectUser = (state) => state.user;
  const user = useSelector(selectUser);
  

  return (
    <div>
      <Avatar image={Logo} />
      <StyledFromArea bg={colors.dark2}>
        <StyledTitle size={65}>Hello, {user}</StyledTitle>
        <Userinfo />
        <ButtonGroup>
          <StyledButton to="#" onClick={() => logoutUser(history)}>
            Logout
          </StyledButton>
        </ButtonGroup>
      </StyledFromArea>
    </div>
  );
};
export default Dashboard;

【讨论】:

  • 我尝试少用
    但它不起作用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多