gpt4 book ai didi

reactjs - 如何在ReactJS中设置路由?

转载 作者:行者123 更新时间:2023-12-03 14:11:08 26 4
gpt4 key购买 nike

我正在尝试设置路由以导航到我的网络应用程序中的不同页面。主页呈现得很好。仅当我尝试导航到不同页面时才会出现这种情况。当我导航到不同的页面时,它返回以下内容:

enter image description here

App.js

import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'
import React from 'react'
import { Component } from 'react';
import ReactDOM from "react-dom"
import Nav from '../navigation/Nav'
import '../css/App.css'
import About from '../components/About'
import Shop from '../components/Shop'

function App(){
return (
<Router>
<div className="App">
<Nav />
<Route path="/about" component={About} />
</div>
</Router>
)
}


export default App

关于.js

import React from 'react'


function About(){
return (
<div className="About">
<h1>This is the About page</h1>
</div>
)
}

export default About

索引.html

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>My React App</title>
</head>

<body>
<div id="app"></div>
</body>

</html>

索引.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App';

index.html
ReactDOM.render( < App /> , document.getElementById('app'));

**编辑:**
版本:

    "dependencies": {
"react": "^16.11.0",
"react-dom": "^16.11.0",
"react-router-dom": "^5.1.2"
}

最佳答案

尝试更改您的 <Router>在 App.js 文件中:

<Router>
<div>
<Nav />
<Switch>
<Route exact component={withRouter({About})} path="/about" />
</Switch>
</div>

您需要使用exact因为它返回任意数量的完全匹配的路由。我添加了switch因为它呈现第一个子项 <Route>与位置匹配。

编辑:您还必须更改您的 Nav成分。导航栏中的链接之一的示例:

<li class="nav-item">
<Link to='/about' class="nav-link" href="/about">About</Link>
</li>

确保包括:import { BrowserRouter as Router, Route, Link, Switch } from 'react-router-dom';在 Nav.js 组件中!

关于reactjs - 如何在ReactJS中设置路由?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58563136/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com