在 React Js 中制作一个独特的列

Making a unique column in React Js

提问人:Sohaib Ahmad Jamil 提问时间:11/11/2023 更新时间:11/11/2023 访问量:11

问:

我面临着一个困惑,我正在尝试制作我的团队组件,我在其中以登录用户的身份填写表单,然后创建我的团队。但是我创建表格的方式并不是一个好主意。下面是我的团队和mongodb连接js。

import React, { useState, useEffect } from 'react';
import { Box, useTheme, TextField, Button } from "@mui/material";
import { DataGrid } from "@mui/x-data-grid";
import { tokens } from "../../theme";
import Header from "../../components/Header";

const Team = () => {
  const theme = useTheme();
  const colors = tokens(theme.palette.mode);
  const [teamMembers, setTeamMembers] = useState([]);
  const [newMember, setNewMember] = useState({
    name: '',
    age: '',
    role: '',
    email: '',
    contactNumber: '',
  });

  useEffect(() => {
    const userID = localStorage.getItem('userID');
    const fetchTeamMembers = async () => {
      try {
        const response = await fetch(`http://localhost:8000/api/team-members?userID=${userID}`);
        if (!response.ok) {
          throw new Error('Server response was not ok.');
        }
        const data = await response.json();
        setTeamMembers(data);
      } catch (error) {
        console.error('Failed to fetch team members:', error);
      }
    };

    fetchTeamMembers();
  }, []);


  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setNewMember(prev => ({ ...prev, [name]: value }));
  };

  const handleFormSubmit = async (e) => {
    e.preventDefault();

    const userID = localStorage.getItem('userID');
    const memberData = { ...newMember, userID };
    const phoneRegex = /^\d{11}$/;

    if (!phoneRegex.test(memberData.contactNumber)) {
      alert('Invalid phone number format. Expected format: + followed by 12 digits');
      return;
    }

    try {
      const response = await fetch('http://localhost:8000/api/team-members', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(memberData),
      });

      if (!response.ok) {
        throw new Error('Failed to post new team member.');
      }

      const addedMember = await response.json();
      setTeamMembers(prev => [...prev, { ...addedMember, id: addedMember._id }]);
      setNewMember({
        name: '',
        age: '',
        role: '',
        email: '',
        contactNumber: '',
      });
    } catch (error) {
      console.error(error);
    }
  };

  const columns = [
    { field: "name", headerName: "Name", flex: 1 },
    { field: "age", headerName: "Age", type: "number", flex: 1 },
    { field: "role", headerName: "Role", flex: 1 },
    { field: "email", headerName: "Email", flex: 1 },
    { field: "contactNumber", headerName: "Contact Number", flex: 1 },
  ];

  return (
    <Box m="20px">
      <Header title="TEAM" subtitle="Managing the Team Members" />
      <Box
        component="form"
        onSubmit={handleFormSubmit}
        noValidate
        display="flex"
        flexDirection="column"
        alignItems="center"
        my={4}
      >
        <TextField
          label="Name"
          name="name"
          value={newMember.name}
          onChange={handleInputChange}
          required
          InputLabelProps={{
            style: { color: 'black' },
          }}
          inputProps={{
            style: { color: 'black' },
          }}
        />
        <TextField
          label="Age"
          name="age"
          type="number"
          value={newMember.age}
          onChange={handleInputChange}
          required
          InputLabelProps={{
            style: { color: 'black' },
          }}
          inputProps={{
            style: { color: 'black' },
          }}
        />
        <TextField
          label="Role"
          name="role"
          value={newMember.role}
          onChange={handleInputChange}
          required
          InputLabelProps={{
            style: { color: 'black' },
          }}
          inputProps={{
            style: { color: 'black' },
          }}
        />
        <TextField
          label="Email (Optional)"
          name="email"
          value={newMember.email}
          onChange={handleInputChange}
          InputLabelProps={{
            style: { color: 'black' },
          }}
          inputProps={{
            style: { color: 'black' },
          }}
        />
        <TextField
          label="Contact Number"
          name="contactNumber"
          value={newMember.contactNumber}
          onChange={handleInputChange}
          required
          InputLabelProps={{
            style: { color: 'black' },
          }}
          inputProps={{
            style: { color: 'black' },
          }}
        />
        <Button type="submit" variant="contained" color="primary">
          Add Member
        </Button>
      </Box>
      <Box
        height="75vh"
        sx={{
          "& .MuiDataGrid-root": {
            border: "none",
          },
          "& .MuiDataGrid-cell": {
            borderBottom: "none",
          },
          "& .name-column--cell": {
            color: colors.greenAccent[300],
          },
          "& .MuiDataGrid-columnHeaders": {
            backgroundColor: colors.blueAccent[700],
            borderBottom: "none",
          },
          "& .MuiDataGrid-virtualScroller": {
            backgroundColor: colors.primary[400],
          },
          "& .MuiDataGrid-footerContainer": {
            borderTop: "none",
            backgroundColor: colors.blueAccent[700],
          },
          "& .MuiCheckbox-root": {
            color: `${colors.greenAccent[200]} !important`,
          },
        }}
      >
        <DataGrid
          checkboxSelection
          rows={teamMembers}
          columns={columns}
          getRowId={(row) => row._id} 
        />

      </Box>
    </Box>
  );

};

export default Team;

至于mongodb.js:

const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const app = express();
const port = 8000;
const { MongoClient } = require('mongodb');

const uri = "mongodb+srv://abc:[email protected]/";
const client = new MongoClient(uri);

async function connectToMongo() {
  try {
    await client.connect();
    console.log("Connected to MongoDB");
  } catch (error) {
    console.error("MongoDB connection error:", error);
    throw error;
  }
}

// Middleware
app.use(cors());
app.use(bodyParser.json());
app.post('/register', async (req, res) => {
  const userData = req.body;
  const usersCollection = client.db('your_database_name').collection('your_collection_name');
  
  try {
    const existingUser = await usersCollection.findOne({ username: userData.username });
    if (existingUser) {
      return res.status(400).json({ message: 'Username already exists' });
    }

    const result = await usersCollection.insertOne(userData);
    const userID = result.insertedId;

    res.status(201).json({ message: 'User registered successfully', userID });
  } catch (error) {
    console.error('Registration error:', error);
    res.status(500).json({ message: 'Registration failed' });
  }
});


app.post('/login', async (req, res) => {
  const { username, password } = req.body;
  const usersCollection = client.db('your_database_name').collection('your_collection_name');

  try {
    const user = await usersCollection.findOne({ username, password });
    if (user) {
      
      const userID = user._id;
      res.status(200).json({ message: 'Login successful', userID });
    } else {
      res.status(401).json({ message: 'Login failed. Invalid credentials' });
    }
  } catch (error) {
    console.error('Login error:', error);
    res.status(500).json({ message: 'Login failed' });
  }
});

app.post('/api/team-members', async (req, res) => {
  const teamMemberData = req.body;
  const teamMembersCollection = client.db('your_database_name').collection('teamMembers');

  try {
    const result = await teamMembersCollection.insertOne(teamMemberData);
    const teamMemberID = result.insertedId;
    res.status(201).json({ message: 'Team member added successfully', teamMemberID });
  } catch (error) {
    console.error('Add team member error:', error);
    res.status(500).json({ message: 'Failed to add team member' });
  }
});

// Endpoint to get all team members
app.get('/api/team-members', async (req, res) => {
  const { userID } = req.query; // Get userID from query parameters
  const teamMembersCollection = client.db('your_database_name').collection('teamMembers');

  try {
    // Cast userID to ObjectId if it's in the ObjectId format
    const query = userID ? { userID: ObjectId(userID) } : {};
    const teamMembers = await teamMembersCollection.find(query).toArray();
    res.status(200).json(teamMembers);
  } catch (error) {
    console.error('Get team members error:', error);
    res.status(500).json({ message: 'Failed to get team members' });
  }
});

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
  connectToMongo();
});

在登录名中,我传递用户名:

import { useState } from 'react';
import { Alert, Button, Snackbar } from '@mui/material';
import Visibility from '@mui/icons-material/Visibility';
import VisibilityOff from '@mui/icons-material/VisibilityOff';
import { useNavigate } from 'react-router-dom';

function LoginPage() {
  const navigate = useNavigate();
  const [currentView, setCurrentView] = useState('signUp');
  const [openSuccessAlert, setOpenSuccessAlert] = useState(false);
  const [showPassword, setShowPassword] = useState(false);
  const [userID, setUserID] = useState(null);
  const changeView = (view) => {
    setCurrentView(view);
  };

  const togglePasswordVisibility = () => {
    setShowPassword(!showPassword);
  };

  const handleLogin = async (event) => {
    event.preventDefault();

    const username = event.target.username.value;
    const password = event.target.password.value;

    try {
      const response = await fetch('http://localhost:8000/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ username, password }),
      });

      if (response.status === 200) {
        // Login was successful
        const data = await response.json();
        const { userID } = data;
        console.log('Login successful');
        console.log('userID:', userID);
        setUserID(userID);
        localStorage.setItem('username', username);
        localStorage.setItem('userID', userID);
        setOpenSuccessAlert(true);
        navigate('/dashboard');
      } else {
        console.error('Login error:', response.status);
      }
    } catch (error) {
      console.error('Network error:', error);
    }
  };
  const handleSignup = async (event) => {
    event.preventDefault();

    const username = event.target.username.value;
    const email = event.target.email.value;
    const password = event.target.password.value;

    try {
      const response = await fetch('http://localhost:8000/register', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ username, email, password }),
      });

      if (response.status === 201) {
        const data = await response.json();
        const { userID } = data;
        console.log('Signup successful');
        console.log('userID:', userID);
        setUserID(userID);
        localStorage.setItem('username', username);
        localStorage.setItem('userID', userID);
        setOpenSuccessAlert(true);
        navigate('/dashboard');
      } else {
        console.error('Signup error:', response.status);
      }
    } catch (error) {
      console.error('Network error:', error);
    }
  };
  const handleCloseSuccessAlert = () => {
    setOpenSuccessAlert(false);
  };

  const currentViewComponent = () => {
    switch (currentView) {
      case 'signUp':
        return (
          <form onSubmit={handleSignup}>
            <h2>Sign Up!</h2>
            <fieldset>
              <legend>Create Account</legend>
              <ul>
                <li>
                  <label htmlFor="username">Username:</label>
                  <input type="text" id="username" name="username" required />
                </li>
                <li>
                  <label htmlFor="email">Email:</label>
                  <input type="email" id="email" name="email" required />
                </li>
                <li>
                  <label htmlFor="password">Password:</label>
                  <div style={{ display: 'flex' }}>
                    <input
                      type={showPassword ? 'text' : 'password'}
                      id="password"
                      name="password"
                      required
                    />
                    <button
                      type="button"
                      onClick={togglePasswordVisibility}
                    >
                      {showPassword ? (
                        <VisibilityOff />
                      ) : (
                        <Visibility />
                      )}
                    </button>
                  </div>
                </li>
              </ul>
            </fieldset>
            <Button type="submit" variant="outlined">
              Submit
            </Button>
            <Button type="button" onClick={() => changeView('logIn')}>
              Have an Account?
            </Button>
          </form>
        );
      case 'logIn':
        return (
          <form onSubmit={handleLogin}>
            <h2>Welcome Back!</h2>
            <fieldset>
              <legend>Log In</legend>
              <ul>
                <li>
                  <label htmlFor="username">Username:</label>
                  <input type="text" id="username" name="username" required />
                </li>
                <li>
                  <label htmlFor="password">Password:</label>
                  <input type="password" id="password" name="password" required />
                </li>
                <li>
                  <i />
                  <button
                    onClick={() => changeView('PWReset')}
                    href="#"
                  >
                    Forgot Password?
                  </button>
                </li>
              </ul>
            </fieldset>
            <Button type="submit" variant="outlined">
              Login
            </Button>
            <Button type="button" onClick={() => changeView('signUp')}>
              Create an Account
            </Button>
          </form>
        );
      case 'PWReset':
        return (
          <form>
            <h2>Reset Password</h2>
            <fieldset>
              <legend>Password Reset</legend>
              <ul>
                <li>
                  <em>A reset link will be sent to your inbox!</em>
                </li>
                <li>
                  <label htmlFor="email">Email:</label>
                  <input type="email" id="email" name="email" required />
                </li>
              </ul>
            </fieldset>
            <Button variant="outlined">Send Reset Link</Button>
            <Button
              type="button"
              onClick={() => changeView('logIn')}
            >
              Go Back
            </Button>
          </form>
        );

      default:
        break;
    }
  };
  return (
    <section id="entry-page">
      {currentViewComponent()}
      <Snackbar
        open={openSuccessAlert}
        autoHideDuration={6000}
        onClose={handleCloseSuccessAlert}
      >
        <Alert
          onClose={handleCloseSuccessAlert}
          severity="success"
          sx={{ width: '100%' }}
        >
          {currentView === 'signUp' ? `Signup successful! Your userID is ${userID}` : `Login successful! Your userID is ${userID}`}
        </Alert>
      </Snackbar>
    </section>
  );
}

export default LoginPage;

我面临的第一件事是我试图插入添加按钮,我可以在其中添加团队行,比如说 user1。但是我的表单不会以弹出窗口的形式从按钮打开。下面是我现在为用户提供的表格,我希望代码应该能够识别当前用户When I log in or sign-up在团队中登录或注册的行。如果他已登录,则应显示“user1”的所有行,同样,如果我创建user2,那么我需要在Team组件中显示他的行。我该怎么做。以下是我制作的失败的集合:Row in the Team

ReactJS 数据库 MongoDB 集合

评论


答: 暂无答案