Создание многостраничного приложения react. Ошибка типа: не удается прочитать свойство ‘pathname’ неопределенного типа

#javascript #reactjs #webpack #react-router #react-dom

#javascript #reactjs #webpack #реагировать-маршрутизатор #react-dom

Вопрос:

Я пытаюсь создать многостраничное приложение с помощью react-router, но я продолжаю получать ошибки такого типа. Я не знаю, как объяснить ситуацию, потому что я новичок в react, но я пытаюсь добавить страницу входа в приложение. Также открыт для новых идей или методов.

Index.html

 
<!--LayoutTop-->
<!DOCTYPE html>
<html lang="zxx">
<head>
  <!--Head Here-->
  <title>AFRIGraphy</title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  
  <link href="%PUBLIC_URL%/img/favicon.ico" rel="shortcut icon" />
  
  <link href="https://fonts.googleapis.com/css?family=Poppins:300,300i,400,400i,500,500i,600,600i,700,700iamp;display=swap" rel="stylesheet">
  
  <link rel="stylesheet" href="%PUBLIC_URL%/css/bootstrap.min.css" type="text/css" />
  <link rel="stylesheet" href="%PUBLIC_URL%/css/font-awesome.min.css" type="text/css" />
  <link rel="stylesheet" href="%PUBLIC_URL%/css/magnific-popup.css" type="text/css" />
  <link rel="stylesheet" href="%PUBLIC_URL%/css/owl.carousel.min.css" type="text/css"/>
  
  <link rel="stylesheet" href="%PUBLIC_URL%/css/style.css" type="text/css"/>
        
  
</head>
<body>

<div id="preloder">
<div class="loader"></div>
</div>
<!--Header Here-->



<div id='root'></div>



<script src="%PUBLIC_URL%/js/jquery-3.2.1.min.js"  type="text/javascript"></script>
<script src="%PUBLIC_URL%/js/bootstrap.min.js"  type="text/javascript"></script>
<script src="%PUBLIC_URL%/js/jquery.slicknav.min.js"  type="text/javascript"></script>
<script src="%PUBLIC_URL%/js/owl.carousel.min.js"  type="text/javascript"></script>
<script src="%PUBLIC_URL%/js/jquery.magnific-popup.min.js"  type="text/javascript"></script>
<script src="%PUBLIC_URL%/js/circle-progress.min.js"  type="text/javascript"></script>
<script src="%PUBLIC_URL%/js/mixitup.min.js"  type="text/javascript"></script>
<script src="%PUBLIC_URL%/js/instafeed.min.js"  type="text/javascript"></script>
<script src="%PUBLIC_URL%/js/masonry.pkgd.min.js"  type="text/javascript"></script>
<script src="%PUBLIC_URL%/js/main.js"  type="text/javascript"></script>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
      <script src="https://unpkg.com/react/umd/react.production.min.js" crossorigin></script>

<script
  src="https://unpkg.com/react-dom/umd/react-dom.production.min.js"
  crossorigin></script>

<script
  src="https://unpkg.com/react-bootstrap@next/dist/react-bootstrap.min.js"
  crossorigin></script>

<script>var Alert = ReactBootstrap.Alert;</script>

<script >
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'UA-23581568-13');
</script>
<script src="https://ajax.cloudflare.com/cdn-cgi/scripts/7089c43e/cloudflare-static/rocket-loader.min.js" data-cf-settings="fdd38016b2c0a37d3fefa1a8-|49" defer=""></script></body>
</html>
<!--EndLayout-->
  

index.js

 import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import './App.scss'
import './App.css'
import * as serviceWorker from './serviceWorker';
import App from './App';
import {BrowserRouter} from 'react-router-dom'

ReactDOM.render(
    <BrowserRouter>
        <React.StrictMode>
            <App/>
        </React.StrictMode>
    </BrowserRouter>,
    document.getElementById('root'))


// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers:
serviceWorker.unregister();
  

App.js

 import { BrowserRouter, Route, Switch } from 'react-router-dom';
import {IntlProvider} from 'react-intl'

 
import Header,{MainRouter} from './components/Header'
//import Contact from './components/Contact';
//import Error from './components/Error';
//import Navigation from './components/Navigation';
 
const App = () => {
  return (
      <div className="app">
        <Header/>
        <MainRouter/>
      </div>
    
  )
  
}
 
export default App;
  

Header.js

 import '../App.css'
import {Nav, Navbar, NavDropdown} from 'react-bootstrap';
import {NavLink} from 'react-router-dom'
import Home from './Home'
import Login from './Login'
import {Switch,Route} from 'react-router-dom'
import {Link} from 'react-router-dom'


class Header extends React.Component {
    render(){
        return [
          <header class="header-section">
  

            <Navbar bg="light" expand="lg">
  <Navbar.Brand href="#home"><img class='site-logo' alt='logo' src={process.env.PUBLIC_URL '/img/logo.png'}/></Navbar.Brand>
  <Navbar.Toggle aria-controls="basic-navbar-nav" />
  <Navbar.Collapse id="basic-navbar-nav">
    <Nav className="ml-auto">
      <Link to="/">Home</Link>
      <NavLink href="#link">Explore</NavLink>
      <NavLink href="#link">Cart</NavLink>
      <Link to="/login">Login</Link>
      <NavLink href="#link">SignUp</NavLink>
    </Nav>
    
    <Nav className='mr-5'>
    <NavDropdown className='mr-3' title={
        <img className='thumbnail-image' src={process.env.PUBLIC_URL '/img/avatar.jpg'} alt='avatar' style={{height:50 , width:50}}  />
        } id="basic-nav-dropdown">
        <NavDropdown.Header title='User'><h6>User</h6></NavDropdown.Header>
        <NavDropdown.Item href="#action/3.1">Orders</NavDropdown.Item>
        <NavDropdown.Item href="#action/3.2">Edit Profile</NavDropdown.Item>
        <NavDropdown.Item href="#action/3.2">Sales</NavDropdown.Item>
        <NavDropdown.Item href="#action/3.2">Security</NavDropdown.Item>
        <NavDropdown.Item href="#action/3.3"></NavDropdown.Item>
        <NavDropdown.Divider />
        <NavDropdown.Item href="#action/3.4">Sign Out</NavDropdown.Item>
      </NavDropdown>
    </Nav>
  </Navbar.Collapse>
</Navbar>
</header>
        ]
    }
}
const MainRouter = () => (
  <Switch>
    <Route exact path='/' component={Home}></Route>
    <Route exact path='/login' component={Login}></Route>
  </Switch>
);

export default Header
export {MainRouter}
  

Home.js

 import React, { useState } from 'react';
import Aside from './Aside';
import Main from './MainContent';

function Home({ setLocale }) {

  const [toggled, setToggled] = useState(false);


  const handleToggleSidebar = (value) => {
    setToggled(value);
  };

  return (
    
    <div className={`app ${toggled ? 'toggled' : ''}`}>
      <Aside
        toggled={toggled}
        handleToggleSidebar={handleToggleSidebar}
      />
      <Main
        toggled={toggled}
        handleToggleSidebar={handleToggleSidebar}
      />
    </div>
  );
}

export default Home;
  

Login.js

 import React,{useState} from 'react'
import {render,hydrate} from 'react-dom'
import '../App.css'
import {Form,Button,Col,as,md,controlId} from 'react-bootstrap'
import App from '../App'

function Login (){

    const [validated, setValidated] = useState(false)
    const handleSubmit = (event) => {
      const form = event.currentTarget;
      if (form.checkValidity() === false) {
        event.preventDefault();
        event.stopPropagation();
      }
  
      setValidated(true);
    }

    return (
        <Form noValidate validated={validated} onSubmit={handleSubmit}>
          <Form.Row>
            <Form.Group as={Col} md="4" controlId="loginEmail">
              <Form.Control
                required
                type="email"
                placeholder="Email"
              />
              <Form.Control.Feedback>Looks good!</Form.Control.Feedback>
            </Form.Group>
            <Form.Group as={Col} md="4" controlId="loginPassword">
              <Form.Control
                required
                type="password"
                placeholder="Password"
              />
              <Form.Control.Feedback>Looks good!</Form.Control.Feedback>
            </Form.Group>
          </Form.Row>
          <Button type="submit">Submit form</Button>
        </Form>
    )
    
    
}
export default Login
  

MainContent.js

 import React from 'react';
import { useIntl } from 'react-intl';
import { FaSearch } from 'react-icons/fa';
import ResponsivePhotoGrid from './ResponsivePhotoGrid'

const Main = ({

  handleToggleSidebar
}) => {
  return (
    <main>
      <div className="btn-toggle" onClick={() => handleToggleSidebar(true)}>
        <FaSearch />
      </div>
      <ResponsivePhotoGrid/>
    </main>
  );
};

export default Main;
  

Aside.js

 import React from 'react';
import { useIntl } from 'react-intl';
import {
  ProSidebar,
  Menu,
  SidebarHeader,
  SidebarFooter,
  SidebarContent,
} from 'react-pro-sidebar';
import { FaGithub} from 'react-icons/fa';
import '../App.scss'
import {Button,Form,FormControl} from 'react-bootstrap'
import FilterHasChildren from './FilterHasChildren'
import FilterHasNoChildren from './FilterHasNoChildren'

const Aside = ({toggled, handleToggleSidebar }) => {
  return (
    <ProSidebar
      toggled={toggled}
      breakPoint="md"
      onToggle={handleToggleSidebar}
    >
      <SidebarHeader>
        <div
          style={{
            padding: '0 24px',
            textTransform: 'uppercase',
            fontWeight: 'bold',
            fontSize: 14,
            letterSpacing: '1px',
            overflow: 'hidden',
            textOverflow: 'ellipsis',
            whiteSpace: 'nowrap',
            align:"center",
          }}
        >
          Find Images
        </div>
      </SidebarHeader>

      <SidebarContent>
        <Menu iconShape="circle">
        <Form inline>
          <FormControl type="text" placeholder="Search" className="ml-sm-2" style={{
            width:240
          }} />
            <Button variant="dark" className="ml-5" action="link-1">#AddTag</Button>
            <Button variant="dark" className="ml-1" action="link-1">Search</Button>
        </Form>
        </Menu>
        <Menu>
          <FilterHasChildren categoryName='Filter1' filterOptions={['Subfilter1','Subfilter2']}/>
          <FilterHasChildren categoryName='Filter2' filterOptions={['Subfilter3','Subfilter4','SubFilter5','SubFilter6','SubFilter7']}/>
          <FilterHasNoChildren categoryfilters={['Filter3','Filter4','Filter6']}/>
          <FilterHasChildren categoryName='Filter7' filterOptions={['Subfilter8','Subfilter9','SubFilter10']}/>
        </Menu>
        
      </SidebarContent>

      <SidebarFooter style={{ textAlign: 'center' }}>
        <div className="sidebar-btn-wrapper">
          <a
            href="https://github.com/azouaoui-med/react-pro-sidebar"
            target="_blank"
            className="sidebar-btn"
            rel="noopener noreferrer"
          >
            <FaGithub />
            <span> View Source</span>
          </a>
        </div>
      </SidebarFooter>
    </ProSidebar>
  );
};

export default Aside;
  

Сообщение об ошибке

 NavLink.js:54 Uncaught TypeError: Cannot read property 'pathname' of undefined
    at NavLink.js:54
    at updateContextConsumer (react-dom.development.js:18304)
    at beginWork (react-dom.development.js:18661)
    at HTMLUnknownElement.callCallback (react-dom.development.js:188)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:237)
    at invokeGuardedCallback (react-dom.development.js:292)
    at beginWork$1 (react-dom.development.js:23203)
    at performUnitOfWork (react-dom.development.js:22154)
    at workLoopSync (react-dom.development.js:22130)
    at performSyncWorkOnRoot (react-dom.development.js:21756)
    at scheduleUpdateOnFiber (react-dom.development.js:21188)
    at updateContainer (react-dom.development.js:24373)
    at react-dom.development.js:24758
    at unbatchedUpdates (react-dom.development.js:21903)
    at legacyRenderSubtreeIntoContainer (react-dom.development.js:24757)
    at Object.render (react-dom.development.js:24840)
    at Module../src/index.js (index.js:11)
    at __webpack_require__ (bootstrap:784)
    at fn (bootstrap:150)
    at Object.1 (serviceWorker.js:141)
    at __webpack_require__ (bootstrap:784)
    at checkDeferredModules (bootstrap:45)
    at Array.webpackJsonpCallback [as push] (bootstrap:32)
    at main.chunk.js:1
  

пакет.json

 {
  "name": "afrireact",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
    "@testing-library/user-event": "^7.2.1",
    "bootstrap": "^4.5.1",
    "node-sass": "^4.14.1",
    "react": "^16.13.1",
    "react-bootstrap": "^1.3.0",
    "react-dom": "^16.13.1",
    "react-icons": "^3.10.0",
    "react-id-generator": "^3.0.1",
    "react-intl": "^5.4.5",
    "react-pro-sidebar": "^0.4.3",
    "react-router-dom": "^5.2.0",
    "react-scripts": "^3.4.3",
    "react-switch": "^5.0.1",
    "slicknav": "^1.0.8"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}
  

Ответ №1:

Забыл изменить компонент NavLink в Header.js чтобы связать и добавить путь