【问题标题】:adding react routes to router in react produces blank page在反应中向路由器添加反应路由会产生空白页面
【发布时间】:2020-11-06 12:35:14
【问题描述】:

每当向我的 react 组件添加路由时,页面都会变为空白且没有错误消息。唯一发生的情况是当我在 Switch 中将路由添加到我的 Nav.js 文件时。这是我的代码:

Nav.js:

import React from "react";
import './Nav.css';
import { BrowserRouter as Router } from 'react-router-dom'
import { NavLink, Switch } from 'react-router-dom';
// import { Routes } from '../routes';
import BrowserRouter
import { Route} from 'react-router-dom';
import Design from "../Design";
import Main from '../Main';


// import Navbar from 'react-bootstrap/Navbar';
// import NavDropdown from 'react-bootstrap/NavDropdown';


const Nav = () => {
    return (
      <Router>
      
      <div className="Nav">
      <div className="head">
       <div id="title">
        WKO
        <div id="bar"></div>
       </div>
       <div className="headlist">
        
         <ul >
         <li><NavLink to="/" style={{color: 'aliceblue', textDecoration: 'none' }} activestyle={{color: 'red'}}>Home</NavLink></li>
         <li><NavLink to="/" style={{color: 'aliceblue', textDecoration: 'none'}} activestyle={{color: 'red'}}>Foundation</NavLink></li>
         <li><NavLink to="/design" style={{color: 'aliceblue', textDecoration: 'none'}} activestyle={{color: 'red'}}>Design</NavLink></li>
         <li><NavLink to="/" style={{color: 'aliceblue', textDecoration: 'none'}} activestyle={{color: 'red'}}>OteyBakes</NavLink></li>
         <li><NavLink to="/" style={{color: 'aliceblue', textDecoration: 'none'}} activestyle={{color: 'red'}}>LLR</NavLink></li>
         <li><NavLink to="/" style={{color: 'aliceblue', textDecoration: 'none'}} activestyle={{color: 'red'}}>Shop</NavLink></li>
         <Switch> 

          <Route exact path='/' component={Main} />
          <Route exact path='/design' component={Design} /> 
          </Switch>
         </ul>
         {/* {Routes} */}
         
         
        
       </div>
      </div> 
      </div>
      </Router>
    );
  }

export default Nav;

提前感谢您的帮助!

【问题讨论】:

  • 你连导航都没看到?您访问的是哪个网址?
  • @BillDoughty 我正在使用 localhost,除了空白页我什么都看不到

标签: javascript reactjs routes react-router react-router-dom


【解决方案1】:

查看沙盒的工作示例:

https://codesandbox.io/s/romantic-noether-27wl4?file=/src/App.js

注意事项:

  • 路由器应该在 index.js 中环绕应用程序
  • switch 和 routes 应该在 app.js 中
  • aliceblue 不是注册的 css 颜色
  • ul listStyleType 删除项目符号,而不是 li textDecoration
  • activestyle 应该是 activeStyle
  • 使用渲染而不是组件属性以获得更好的性能
  • 映射您的路线而不是硬编码以获得更简洁的代码

【讨论】:

    【解决方案2】:

    没有工作代码有点难说, 但您可以尝试更改 NavLink 和 Route:

    <NavLink exact to="/" style={{/*your style'/}} activestyle={{color: 'red'}}>Home</NavLink>
    

    <Route path='/design' exact component={Design}></Route>
    

    如果不起作用,您可以在此处https://codesandbox.io/ 发布您的代码,以帮助您。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-23
      • 2021-08-22
      • 2018-08-17
      • 2021-02-21
      • 2017-12-08
      • 2022-01-01
      • 1970-01-01
      • 2021-01-22
      相关资源
      最近更新 更多