将管理属性从父组件传递到子组件

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

import React, { useState, useEffect } from "react";
import SignUpForm from "../SignUpForm/SignUpForm";
import { getUser } from "../../utilities/users-service";
import Home from "../Home/Home";
import { Routes, Route } from "react-router-dom";
import Logout from "../Logout/Logout";
import LoginForm from "../LoginForm/LoginForm";
import NavBar from "../../NavBar/NavBar";
import Footer from "../Footer/Footer";
import OneGame from "../OneGame/OneGame";
import Cart from "../Cart/Cart";
import AdminComponent from "../Admin/AdminComponent"; // Import the Admin Component

function CleanUp() {
  const [user, setUser] = useState(getUser());
  const [admin, setAdmin] = useState(false);

  // Check if user is logged in and has a role of "admin"
  useEffect(() => {
    if (user && user.role === "admin") {
      setAdmin(true);
      console.log("you are a admin");
    } else {
      setAdmin(false);
      console.log("you are not an admin :(");
    }
  }, [user]);

  return (
    <div>
      <NavBar setUser={setUser} user={user} />

      <Routes>
        {user ? (
          <>
            <Route
              path="/home"
              element={<Home user={user} setUser={setUser} />}
            />
            <Route
              path="/logout"
              element={
                <Logout
                  setUser={setUser}
                  user={user}
                  admin={admin}
                  setAdmin={setAdmin}
                />
              }
            />
            <Route
              path="/home/:id"
              element={<OneGame setUser={setUser} user={user} />}
            />
            <Route
              path="/cart"
              element={<Cart setUser={setUser} user={user} />}
            />
            {admin && (
              <Route
                path="/admin"
                element={
                  <AdminComponent setUser={setUser} user={user} admin={admin} />
                }
              />
            )}
          </>
        ) : (
          <>
            <Route
              path="/signup"
              element={
                <SignUpForm
                  setUser={setUser}
                  user={user}
                  admin={admin}
                  setAdmin={setAdmin}
                />
              }
            />
            <Route
              path="/*"
              element={<LoginForm setUser={setUser} user={user} />}
            />
          </>
        )}
      </Routes>
      <Footer />
    </div>
  );
}

export default CleanUp;

我将道具从父组件传递到我的子注册表单,我可以毫无问题地登录和注册(这样做的目的是,如果用户具有“管理员”角色,则该管理员可以创建游戏、删除等)。而普通用户只能看到视频游戏并添加到购物车。但是,我无法分配角色,每当我进入路由 localhost3000/admin 时,它都会显示空白,我路由到的组件只有一个标签,没有什么特别的。这里出了什么问题?为什么我的用户在注册时没有设置为管理员,即使我设置为 true? working onchange有什么帮助吗? parent component [子组件works login](https://i.stack.imgur.com/dE0Lq.jpg)

子组件:

import React, { useState } from "react";
import { signUp } from "../../utilities/users-service";
import { useNavigate } from "react-router-dom";
import styles from "./SignUpForm.module.css";
import { Link } from "react-router-dom";

export default function SignUpForm({ setUser, user, admin, setAdmin }) {
  const [state, setState] = useState({
    name: "",
    email: "",
    password: "",
    confirm: "",
    error: "",
  });

  let navigate = useNavigate();

  const handleChange = (evt) => {
    const { name, value } = evt.target;
    setState({ ...state, [name]: value, error: "" });

    // Check if the selected role is "admin" and update the admin state accordingly
    if (name === "role" && value === "admin") {
      setAdmin(true);
      console.log("admin role is true");
    } else {
      setAdmin(false);
      console.log("admin role is false");
    }
  };

  const handleSubmit = async (evt) => {
    evt.preventDefault();

    try {
      const formData = { ...state };
      delete formData.error;
      delete formData.confirm;

      const newUser = await signUp(formData);
      setUser(newUser);
      navigate("/home");
    } catch (err) {
      console.log(err);
      setState({ error: "Sign Up Failed" });
    }
  };

  const disable = state.password !== state.confirm;

  return (
    <div>
      <style>{"body { background: linear-gradient(#141e30, #243b55)}"}</style>
      <div className={styles.loginbox}>
        <h2>SignUp</h2>
        <h5>
          Need to Login ?
          <Link className="nav-link active" to="/login">
            <button>
              <em>Click Here</em>
            </button>
          </Link>
        </h5>
        <form autoComplete="off" onSubmit={handleSubmit}>
          <div className={styles.userbox}>
            <input
              type="text"
              name="name"
              value={state.name}
              onChange={handleChange}
              required
            />
            <label>Name</label>
          </div>

          <div className={styles.userbox}>
            <input
              type="email"
              name="email"
              value={state.email}
              onChange={handleChange}
              required
            />
            <label>Email</label>
          </div>

          <div className={styles.userbox}>
            <input
              type="password"
              name="password"
              value={state.password}
              onChange={handleChange}
              required
            />
            <label>Password</label>
          </div>

          <div className={styles.userbox}>
            <input
              type="password"
              name="confirm"
              value={state.confirm}
              onChange={handleChange}
              required
            />
            <label>Confirm</label>
          </div>

          <div className={styles.userbox}>
            <select
              name="role"
              id="role"
              value={state.role}
              onChange={handleChange}
            >
              <option value="user">Player</option>
              <option value="admin">Admin</option>
            </select>
          </div>

          <button type="submit" disabled={disable}>
            <span></span>
            <span></span>
            <span></span>
            <span></span>
            Sign Up
          </button>
        </form>
      </div>
      <p className="error-message">
        &nbsp;{state.error} <style>{"body { background: color)}"}</style>
      </p>
    </div>
  );
}

node.js reactjs mongodb react-router react-props
1个回答
0
投票

else
中的
handleChange
函数中的
SignUpForm
块可能是问题所在。您在所有输入中使用该函数,因此即使在更新名称时也可以调用
setAdmin(false)
,例如,因为
if (name === "role" && value === "admin")
条件在所有其他输入中均为 false。

也就是说,我认为似乎也存在一些架构问题,通过

setUser
setAdmin
似乎很奇怪。

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