[英]React Router doesn't display component when route is matched (but render works)
I am trying to learn React
and using Create-React-App
to experiment. 我正在尝试学习
React
并使用Create-React-App
进行实验。
Today I was trying to learn how to use React Router
, but I couldn't make it work. 今天,我试图学习如何使用
React Router
,但是我无法使其工作。
Here is my code: ( App.js
) 这是我的代码:(
App.js
)
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import { BrowserRouter as Router, Route, Link, NavLink, Switch } from 'react-router-dom'
import { Navbar, Jumbotron, Button } from 'react-bootstrap';
class App extends Component {
render() {
const baseUrl = process.env.PUBLIC_URL;
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">React Star Wars Table Test</h1>
</header>
<Router>
<div>
<NavLink to={baseUrl + '/Foo'}>Foo</NavLink> <NavLink to={'/Bar'}>Bar</NavLink>
<hr />
<Switch>
<Route path="/" exact render={() => (<h1>HOME</h1>)} />
<Route path={baseUrl + "/Foo"} exact Component={Foo} />
<Route path='/Bar' exact Component={Bar} />
</Switch>
</div>
</Router>
</div>
);
}
}
class Foo extends Component {
render() {
return (
<p>Foo!</p>
);
}
}
class Bar extends Component {
retnder(){
return (
<h1>Bar!</h1>
);
}
}
export default App;
The issue is that the routes don't display the components when they match the URL (either clicking on the NavLinks or manually typing the URL). 问题在于,当路线与URL匹配时,它们不会显示组件(单击NavLinks或手动键入URL)。
The base ('/') route works and displays the HOME H1. 基本('/')路线有效并显示HOME H1。
I know the routes are matching because if I try to use the render
attribute for all the routes, it works. 我知道这些路由是匹配的,因为如果我尝试对所有路由使用
render
属性,它将起作用。
Switch
tag, but I have tried also without, same result. Switch
标记,但我也尝试了相同的结果。 NavLink
and a Route
with a baseUrl const and one without, I have tried either way (none, both, one yes and one not), same result. NavLink
和一个带有NavLink
const的Route
,一个没有,我尝试了两种方法(无,两者,一个是,一个不是),结果相同。 采用组件的Route
的支持称为component
,而不是具有大写c
Component
。
<Route path='/Bar' exact component={Bar} />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.