页面无法正确加载,除非我刷新

问题描述 投票:0回答:1

我有一个使用 React 的珠宝店应用程序,有两种类型的用户:管理员和客户。管理员可以查看包含所有用户的表格以及用户是否在线或离线。我通过为每个客户添加一个活动属性来做到这一点,当有人成功登录时,活动属性将变为 1(在线),否则为 0(离线)。我用于注销的想法相同。 问题是,活动列中的更改无法正确加载,除非我用表格刷新页面,它保持在它的最后状态,所以问题出在前端,我不知道到底在哪里。 这是登录页面:

import axios from "axios";
import React, { useState, useEffect } from "react";
import { Link, useNavigate } from "react-router-dom";

export default function Login() {
  const navigate = useNavigate();
  const [customer, setCustomer] = useState({
    email: "",
    password: "",
  });



  const [onlineusers, setOnline] = useState([]); // State to track online/offline status

  useEffect(() => {
    // Load online/offline status when component mounts
    loadOnlineStatus();
  }, []);



  const { email, password } = customer;

  const onInputChange = (e) => {
    setCustomer({ ...customer, [e.target.name]: e.target.value });
  };

  const loadOnlineStatus = async () => {
    // try {
      const response = await axios.get("http://localhost:8080/customers");
      setOnline(response.data);
    // } catch (error) {
    //   console.error("Error loading online status:", error);
    // }
  };

  const onSubmit = async (e) => {
    e.preventDefault();
  
    try {
      const response = await axios.get(
        `http://localhost:8080/customerEmail?email=${email}&password=${password}`
      );
  
      const loggedInCustomer = response.data;
  
      if (loggedInCustomer) {
        console.log("Login successful:", loggedInCustomer);

        await axios.put(`http://localhost:8080/customeron/${email}`);
        loadOnlineStatus();

        //stocare email
        localStorage.setItem('loggedInEmail', email);
        const role = await axios.get(
            `http://localhost:8080/role?email=${email}&password=${password}`
        );

        

        if (role.data==="ADMIN") {
          navigate("/admin");
        } else {
          navigate("/customer");
        }
      } else {
        console.error("Login failed");
      }
    } catch (error) {
      console.error("Error during login:", error);
    }
  };
  

  return (
    <div className="container">
      <div className="row">
        <div className="col-md-6 offset-md-3 border rounded p-4 mt-2 shadow">
          <h2 className="text-center m-4">Log In</h2>

          <form onSubmit={(e) => onSubmit(e)}>
            <div className="mb-3">
              <label htmlFor="Email" className="form-label">
                E-mail
              </label>
              <input
                type="text"
                className="form-control"
                placeholder="Enter your e-mail address"
                name="email"
                value={email}
                onChange={(e) => onInputChange(e)}
              />
            </div>
            <div className="mb-3">
              <label htmlFor="Password" className="form-label">
                Password
              </label>
              <input
                type="password" 
                className="form-control"
                placeholder="Enter your password"
                name="password"
                value={password}
                onChange={(e) => onInputChange(e)}
              />
            </div>

            <button type="submit" className="btn btn-outline-danger mx-2">
              Log In
            </button>
            <Link className="btn btn-outline-danger mx-2" to="/register">
              Sign Up
            </Link>
          </form>
        </div>
      </div>
    </div>
  );
}

这是我的在线用户页面:

import React, { useEffect, useState } from "react";
import axios from "axios";
import { Link } from "react-router-dom";

export default function OnlineUsers() {
  const [users, setUsers] = useState([]);


  useEffect(() => {
    loadUsers();
  }, []);

  const loadUsers = async () => {
    const result = await axios.get("http://localhost:8080/customers");
    setUsers(result.data);
  };

  return (
    <div className="container">
      <div className="py-4">
        <table className="table border shadow">
          <thead>
            <tr>
              <th scope="col">ID</th>
              <th scope="col">Name</th>
              <th scope="col">Username</th>
              <th scope="col">Email</th>
              <th scope="col">Online Activity</th>
            </tr>
          </thead>
          <tbody>
            {users.map((user, index) => (
              <tr>
                <th scope="row" key={index}>
                  {index + 1}
                </th>
                <td>{user.name}</td>
                <td>{user.username}</td>
                <td>{user.email}</td>
                <td>{user.activ===0 ? "Offline" : "Online"}</td>
              </tr>
            ))}
          </tbody>
        </table>
        <Link
          className="btn btn-outline-primary mx-2"
          to={`/admin`}
        >
          Back
        </Link>
      </div>
    </div>
  );
}

这是获取所有客户的控制器功能:

@GetMapping("/customers")
List<Customer> getAllCustomers() {
    return customerService.findAll();
}
java reactjs
1个回答
0
投票

一个简单的解决方案是使用

setInterval
定期获取用户数据:

  useEffect(() => {
    loadUsers();

    const interval = setInterval(() => {
      loadUsers();
    }, 5000); // 5s

    return () => clearInterval(interval);
  }, []);

如果要实现实时更新,可能需要使用WebSocket,但是需要后端和前端都做出改变

© www.soinside.com 2019 - 2024. All rights reserved.