Предупреждение: React.jsx: недопустимый тип -- ожидается строка

У меня возникла ошибка с кодом Login.js, это показанная ошибка. У меня также есть проблема с навигацией в заголовке, пожалуйста, помогите мне, это рабочий веб-сайт CRUD.

Warning: React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
Check your code at login.js:36.
    at Login (http://localhost:3000/static/js/bundle.js:482:75)
    at RenderedRoute (http://localhost:3000/static/js/bundle.js:42128:5)
    at Routes (http://localhost:3000/static/js/bundle.js:42571:5)
    at Router (http://localhost:3000/static/js/bundle.js:42509:15)
    at BrowserRouter (http://localhost:3000/static/js/bundle.js:40827:5)
    at div
    at div
    at App

У меня также есть проблема с навигацией в заголовке, пожалуйста, помогите мне, это сайт операции CRUD.

App.js

import './App.css';
import Create from './components/create';
import Read from './components/read';
import Update from './components/update';
import Login from './components/login';
import { Routes, Route } from 'react-router-dom';
import { BrowserRouter } from 'react-router-dom';
// import { useNavigate } from 'react-router-dom';

// import { Link } from 'react-router-dom';                                                
// import Header from './components/header';

function App() {
  // let Navigate = useNavigate();

  return ( 
    <div>
    <header>
<h1 class='header1'>Aman Enterprises</h1>
<nav class ='nav'>
  <ul>
    {/* <li><Link to = '/login'>Login</Link></li> */}
    {/* <li><Link to = '/create'>Registration</Link></li> */}
  </ul>
</nav>
</header>
    <div className = "main">
      <BrowserRouter>
        <Routes>
          <Route path = "/" element = {<Create />} />
          <Route path = "login" element = {<Login />} />
          <Route path = "read" element = {<Read />} />
          <Route path = "update" element = {<Update />} />
        </Routes>
      </BrowserRouter>
      </div>
    </div>
  );
}

export default App;

Логин.js

import React, { useState } from 'react'
import { Button, Form } from 'semantic-ui-react'
import axios from 'axios'
import { useNavigate } from 'react-router'

export default function Login() {
    let navigate = useNavigate()

    const[username, setusername] = useState('');
    const[Employee_password, setEmployee_password] = useState('');
    
    const GetData = (e) =>{
         e.preventDefault();
        console.info(username, Employee_password)


    if (username !== username && Employee_password !== Employee_password)
    {
        alert('Username or Password does not match!')
        return false
    }
    axios.post('http://localhost:5000/emp/login',{
        username,
        Employee_password
    }).then((res)=>{
        console.info('Login Successfull')
        navigate('/read')
    }).catch(err=>{
        console.info(err)
    })
    }
return(
    <div>
        <Form onCLick = {GetData}>
        <h2>Login into existing ID</h2>
        <Form.field>
            <label>Enter Username</label>
            <input type='text' placeholder='Username' onChange = {(e) => setusername(e.target.value)}></input>
        </Form.field>
        <Form.field>
            <label>Passworld</label>
            <input type='password' placeholder='Password' onChange = {(e) => setEmployee_password(e.target.value)}></input>
        </Form.field>
        {/* {<error && <div style = {{ color: 'red' }}>Error</div>>} */}
        <Button type='submit'>Login</Button>
        </Form>
    </div>
 )
}

создать.js

import React, { useState } from 'react';
import { Button, Form } from 'semantic-ui-react'
import axios from 'axios';
import { useNavigate } from 'react-router';

export default function Create() {
    let navigate = useNavigate();
    const [Employee_name, setEmployee_name] = useState('');
    const [Employee_id, setEmployee_id] = useState('');
    const [Employee_address, setEmployee_address] = useState('');
    const [Employee_post, setEmployee_post] = useState('');
    const [username, setusername] = useState('');
    const [Employee_password, setEmployee_password] = useState('');   

    const postData = (e) => {
        e.preventDefault();
        
        if (Employee_name, Employee_id, Employee_address, Employee_post, username, Employee_password.length === 0)
        {
            alert('Enter Employee Details to register!')
            return false
        }

        if (Employee_name.length === 0)
        {
            alert('Enter Employee Name!')
             return false
        }
        if (Employee_id.length === 0)
        {
            alert('Enter Employee id!')
            return false
        }
        if (Employee_address.length === 0)
        {
            alert('Enter Employee address!')
            return false
        }
        if (Employee_post.length === 0)
        {
            alert('Enter Employee Position!')
            return false
        }
        if (username.length === 0)
        {
            alert('Set Employee Username!')
            return false
        }
        if (Employee_password.length === 0)
        {
            alert('Set Employee Password!')
            return false
        }

        axios.post(`http://localhost:5000/qo`, {
            Employee_name,
            Employee_id,
            Employee_address,
            Employee_post,
            username,
            Employee_password

        })
        .then(() => {
            navigate('/Login')
        })
    
        alert('Data Saved')
    }
    return (
        <div>            
            <Form className = "create-form" onSubmit = {e =>postData(e)}>
            <h2 class='Header'>Employee Registration form</h2>
                <Form.Field required = {true}>
                    <label>Employee Name</label>
                    <input type='text' placeholder='Employee Name' onChange = {(e) => setEmployee_name(e.target.value)}/>
                </Form.Field>
                <Form.Field required = {true}>
                    <label>Employee ID</label>
                    <input type='text' placeholder='Employee ID' onChange = {(e) => setEmployee_id(e.target.value)}/>
                </Form.Field>
                <Form.Field required = {true}>
                    <label>Employee Address</label>
                    <input type='text' placeholder='Employee Address' onChange = {(e) => setEmployee_address(e.target.value)}/>
                </Form.Field>
                <Form.Field required = {true}>
                    <label>Employee Position</label>
                    <input type='text' placeholder='Employee Position' onChange = {(e) => setEmployee_post(e.target.value)}/>
                </Form.Field>
                <Form.Field required = {true}>
                    <label>Create Username</label>
                    <input type='text' placeholder='Username' onChange = {(e) => setusername(e.target.value)}/>
                </Form.Field>
                <Form.Field required = {true}>
                    <label>Create Password</label>
                    <input type='password' placeholder='Password' onChange = {(e) => setEmployee_password(e.target.value)}/>
                </Form.Field>
                <Button class='b2' onClick = {postData} type='submit'>Submit</Button>
            </Form>
        </div>
    )
}

read.js (панель для отображения базы данных с функциями обновления и удаления)

import axios from 'axios';
import React, { useEffect, useState } from 'react';
import { Table, Button } from 'semantic-ui-react';
import { useNavigate } from 'react-router-dom';

export default function Read() {
    let navigate = useNavigate();
    
    const [APIData, setAPIData] = useState([]);
    useEffect(() => {
        axios.get(`http://localhost:5000/emp`)
            .then((response) => {
                console.info(response.data)
                setAPIData(response.data);
            })
    }, []);

    const setData = (data) => {
        let { Employee_name, Employee_id, Employee_address, Employee_post, username, Employee_password } = data;
  
        localStorage.setItem('Employee ID', Employee_id);

        navigate('/update')}

    const getData = () => {
        axios.get(`http://localhost:5000/emp`)
            .then((getData) => {
                setAPIData(getData.data);
            })
    }

    const onDelete = (data) => {

        const{Employee_id}=data
        if (Employee_id===0){
            alert("Employee id not found")
            return
        }
        const url=`http://localhost:5000/emp/${Employee_id}`
        axios.delete(url)
        .then((res) => {
            getData();
        })
        .catch(err=>console.info(err))
        alert('Employee Deleted!')
    }


    const Data = () => {
            navigate('/')
    }

    return (
        <form>
            <h2>Registered Employees</h2>
        <div>
            <Table singleLine>
                <Table.Header>
                    <Table.Row>
                        <Table.HeaderCell>Employee Name</Table.HeaderCell>
                        <Table.HeaderCell>Employee ID</Table.HeaderCell>
                        <Table.HeaderCell>Employee Address</Table.HeaderCell>
                        <Table.HeaderCell>Employee Position</Table.HeaderCell>
                        <Table.HeaderCell>Employee Username</Table.HeaderCell>
                        <Table.HeaderCell>Employee Password</Table.HeaderCell>             
                        
                        <Table.HeaderCell>Update</Table.HeaderCell>
                        <Table.HeaderCell>Delete</Table.HeaderCell>
                    </Table.Row>
                </Table.Header>

                <Table.Body>
                    {APIData.map((data,index) => {
                        return (
                            <Table.Row key = {index+""}>
                                <Table.Cell>{data.Employee_name}</Table.Cell>
                                <Table.Cell>{data.Employee_id}</Table.Cell>
                                <Table.Cell>{data.Employee_address}</Table.Cell>
                                <Table.Cell>{data.Employee_post}</Table.Cell>
                                <Table.Cell>{data.username}</Table.Cell>
                                <Table.Cell>{data.Employee_password}</Table.Cell>
                                
                                {/* <Link to='/update'> */}
                                    <Table.Cell> 
                                        <Button onClick = {() => setData(data)}>Update</Button>
                                    </Table.Cell>
                                {/* </Link> */}
                                <Table.Cell>
                                    <Button onClick = {() => onDelete(data)}>Delete</Button>
                                </Table.Cell>
                            </Table.Row>
                        )
                    })}
                </Table.Body>
            </Table>
            <Button onClick = {Data} type='submit'>Home</Button>
        </div>
        </form>
        
    )
}

update.js

import React, { useState, useEffect } from 'react';
import { Button, Form } from 'semantic-ui-react'
import axios from 'axios';
import { useNavigate } from 'react-router-dom';

export default function Update() {
    let navigate = useNavigate();
    
    const [Employee_name, setEmployee_name] = useState('');
    const [Employee_id, setEmployee_id] = useState('');
    const [Employee_address, setEmployee_address] = useState('');
    const [Employee_post, setEmployee_post] = useState('');
    const [username, setusername] = useState('');
    const[Employee_password, setEmployee_password] = useState('');


    
    useEffect(() => {
        setEmployee_id(localStorage.getItem('Employee ID'));
        const id=localStorage.getItem('Employee ID')
        getEmplyeeDetailsById(id)

        
    }, []);

   const getEmplyeeDetailsById=(id)=>{
       const url=`http://localhost:5000/emp/${id}`
    axios.get(url)
        .then((res) =>{
if (res && res.data){
    console.info(res.data[0])
    let { Employee_name, Employee_id, Employee_address, Employee_post, username, Employee_password } =res.data[0];
    setEmployee_name(Employee_name)
    setEmployee_id(Employee_id)
    setEmployee_address(Employee_address)
    setEmployee_post(Employee_post)
    setusername(username)
    setEmployee_password(Employee_password)
    

}
            // setAPIData(update.data);
        })
        .catch(err=>console.info(err))
    }
    const updateAPIData = () =>{
    let jsonData = {
        Employee_name,
        Employee_id,
        Employee_address,
        Employee_post,
        username,
        Employee_password
    }
        axios.put(`http://localhost:5000/emp/update`, jsonData)
        .then(() => {
            navigate('/read')
        })
    }

    const back = () => {
        navigate('/read')
}


    return (
        <div>
            <Form className = "create-form">
            <h2>Update the Registered Data</h2>
            <Form.Field>
                    <label>Employee Name</label>
                    <input placeholder='Employee Name' value = {Employee_name} onChange = {(e) =>setEmployee_name(e.target.value)}/>
                </Form.Field>
                <Form.Field>
                    <label>Employee ID</label>
                    <input placeholder='Employee ID' value = {Employee_id+""} onChange = {(e) => setEmployee_id(e.target.value)}/>
                </Form.Field>
                <Form.Field>
                    <label>Employee Address</label>
                    <input placeholder='Employee Address' value = {Employee_address} onChange = {(e) => setEmployee_address(e.target.value)}/>
                </Form.Field>
                <Form.Field>
                    <label>Employee Position</label>
                    <input placeholder='Employee Position' value = {Employee_post} onChange = {(e) => setEmployee_post(e.target.value)}/>
                </Form.Field>
                <Form.Field>
                    <label>Username</label>
                    <input placeholder='username' value = {username} onChange = {(e) => setusername(e.target.value)}/>
                </Form.Field>
                <Form.Field>
                    <label>Password</label>
                    <input type='password' placeholder='Password' onChange = {(e) => setEmployee_password(e.target.value)}/>
                </Form.Field>
                <Button type='submit' onClick = {updateAPIData}>Update</Button>
                <Button onClick = {back} type='submit'>Back</Button> 
            </Form>
        </div>
    )
}

Мне кажется опечатка -> <error && vs error &&

Randy Casburn 02.02.2023 06:59

используйте useEffect, когда у вас есть асинхронная логика, или лучше, как это было предложено реакцией, используйте зависимость, такую ​​​​как инструментарий сокращения, или, что еще лучше, используйте запрос набора инструментов сокращения.

Normal 02.02.2023 07:24
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Безумие обратных вызовов в javascript [JS]
Безумие обратных вызовов в javascript [JS]
Здравствуйте! Юный падаван 🚀. Присоединяйся ко мне, чтобы разобраться в одной из самых запутанных концепций, когда вы начинаете изучать мир...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
JavaScript Вопросы с множественным выбором и ответы
JavaScript Вопросы с множественным выбором и ответы
Если вы ищете платформу, которая предоставляет вам бесплатный тест JavaScript MCQ (Multiple Choice Questions With Answers) для оценки ваших знаний,...
1
2
59
2
Перейти к ответу Данный вопрос помечен как решенный

Ответы 2

В App.js вы должны использовать «/» перед каждым путем. Например: путь="/логин". В логин.js. Используйте хук useEffect для выполнения функции. Пример:

useEffect(()=>{GetData () },[])

Я надеюсь, что это будет полезно для вас

Это решит проблему навигации в заголовочной части кода, но все же у меня есть проблема со строкой React.jsx: тип недействителен - ожидается строка (для встроенных компонентов) или класс/функция (для составных компонентов), но получил: не определено. Вероятно, вы забыли экспортировать свой компонент из файла, в котором он определен, или вы могли перепутать импорт по умолчанию и именованный импорт.

Aman Pradhan 02.02.2023 07:29
Ответ принят как подходящий

Замените Form.field на Form.Field в файле Login.js.

Другие вопросы по теме