by Emmanuel Yusufu
通过伊曼纽尔·尤苏夫
React Router 4入门指南 (Beginner’s Guide to React Router 4)
React is a JavaScript library for building user interfaces. With the React paradigm, every piece of the UI is a component that manages its own self-contained state (data) and functions.
React是一个用于构建用户界面JavaScript库。 使用React范例,UI的每个部分都是一个组件,用于管理自己的独立状态(数据)和功能。
React, like other front-end JavaScript frameworks, is useful for creating Single Page Applications (SPAs). These are web apps that do not need a full page reload on change of view. Instead they swap views into or out from a section of the page as the user navigates through the app.
像其他前端JavaScript框架一样,React对创建单页应用程序(SPA)很有用。 这些是无需更改视图即可重新加载整个页面的Web应用程序。 相反,它们在用户浏览应用程序时将视图交换到页面的一部分中或从页面的一部分中交换出来。
Though SPAs provide a fluid navigation experience for users, routing features of traditional websites are expected.
尽管SPA为用户提供了流畅的导航体验,但传统网站的路由功能还是值得期待的。
For instance:
例如:
- every view on the screen should have its own specific URL so I can bookmark the page. 屏幕上的每个视图都应具有其自己的特定URL,因此我可以将页面添加为书签。
- The forward and back button should move me forward or backward in my browsing history. 前进和后退按钮应使我在浏览历史记录中向前或向后移动。
Nested views and those with parameters should be supported, such as
example.com/products/shoes/101
.应支持嵌套视图和带有参数的视图,例如
example.com/products/shoes/101
。
In the React community, React Router is the favorite library for handling routing. The most compelling aspect of this version of the library is that it’s “just React”. The routes are just components that get rendered to the screen when the app is running. They are not defined in external files as done in other frameworks.
在React社区中,React Router是最喜欢的用于处理路由的库。 该库版本的最引人注目的方面是它只是“ React”。 路线只是在应用程序运行时呈现在屏幕上的组件。 它们没有像其他框架一样在外部文件中定义。
先决条件 (Prerequisites)
You will need the following: Basic knowledge of React, Git installed on your computer, and NPM installed on your computer.
您将需要以下内容: 基本知识如React , 计算机上安装的 Git以及计算机 r 上安装的 NPM 。
配置 (Setting Up)
If you have Git installed locate the empty source files (at the master branch) and clone to your computer using:
如果已安装Git,请找到空的源文件 (在master分支),然后使用以下命令克隆到计算机上:
git clone https://github.com/emmyyusufu/react-router-demos.git
Open the folder in your text editor and discover the sub-folders inside:
在文本编辑器中打开文件夹,然后找到其中的子文件夹:
This post is divided into four subsections according to the folders which are: Basic routing
, Nested routing
, Nested routing with path parameters
and Authenticated routing
.
这篇文章根据文件夹分为四个小节: Basic routing
, Nested routing
, Nested routing with path parameters
和Authenticated routing
。
To launch the demos, open a given folder in your terminal then run npm install
followed by npm start
.
要启动演示,请在终端中打开一个给定的文件夹,然后运行npm install
和npm start
。
1基本路由 (1 Basic routing)
Lets start out from scratch. Notice the folder structure of the basic routing folder.
让我们从头开始。 请注意基本路由文件夹的文件夹结构。
All the demos in this post have been initially created using create-react-app. This brings some benefits such an already configured Webpack server that would bundle all the JavaScript file in our app into a bundle.js
file that would be attached into the index.html
file at run time. At run time Webpack’s dev server will listen to any change in our file and update it as the app runs during development.
这篇文章中的所有演示都是使用create-react-app最初创建的。 这带来了一些好处,例如已经配置的Webpack服务器会将我们应用程序中的所有JavaScript文件捆绑到bundle.js
在运行时将附加到index.html
文件中的文件。 在运行时,Webpack的开发服务器将侦听文件中的任何更改,并在应用程序在开发过程中运行时对其进行更新。
I’ve created a components/
folder to keep all our components. Note that:
我已经创建了一个components/
文件夹来保留我们所有的组件。 注意:
index.js
is the entry file to all.js
files in our app. This is where Webpack’s bundling will be performed so all.js
files should be imported into it.index.js
是所有.js
的入口文件 应用中的文件。 这是将执行Webpack捆绑的地方,因此所有.js
档案 应该导入其中。App.js
file will contain everything pertaining to our React app.App.js
文件将包含与我们的React应用有关的所有内容。
By default, create-react-app does not place App.js
in this folder. But because I’ve modified the folder structure, I made the appropriate changes to the path url and imported it into index.js
. To learn more about create-react-app, this reference would be helpful.
默认情况下,create-react-app不会将App.js
放置在此文件夹中。 但是,因为我已经修改了文件夹结构,所以我对路径url进行了适当的更改,并将其导入到index.js
。 要了解有关create-react-app的更多信息,此参考会有所帮助。
Navigate to the first folder 01-basic-routing
and run npm install
.
导航到第一个文件夹01-basic-routing
并运行npm install
。
Open the App.js
file and you should see the following:
打开App.js
文件,您应该看到以下内容:
import React, { Component } from 'react';import '../styles/App.css';
// import route Components here
class App extends Component { render() { return ( <div className="App">
<div className="container"> <ul> <li><a href="">Hello</a></li> <li><a href="">About</a></li> <li><a href="">Books</a></li> </ul> <hr/>
{/* Routes will go here */}
</div>
</div> ); }}
export default App;
Run npm start and view the app. No changes made yet.
运行npm start并查看该应用程序。 尚未进行任何更改。
Lets install React Router via NPM. With the folder open in your terminal, run:
让我们通过NPM安装React Router。 在终端中打开文件夹的情况下,运行:
npm install react-router-dom
Why react-router-dom
? This is because the React router library comprises of three packages: react-router
, react-router-dom
, and react-router-native
.
为什么要react-router-dom
? 这是因为React路由器库包含三个包: react-router
, react-router-dom
和react-router-native
。
react-router
is the core package for the router, whereas the other two are environment specific. You should use react-router-dom
if you’re building for the web, and react-router-native
if you’re on a mobile app development environment using React Native.
react-router
是react-router
的核心软件包,而其他两个是特定于环境的。 你应该使用react-router-dom
,如果您正在为Web和react-router-native
如果你在使用移动应用程序开发环境中相互React原住民。
Import the following into App.js
将以下内容导入App.js
// import route Components hereimport { BrowserRouter as Router, Route, Link, Switch, Redirect} from 'react-router-dom'
Later on we will understand what those components do. All of the routing components depend on BrowserRouter
to provide the browser’s HTML5 History APIs to them.
稍后我们将了解这些组件的作用。 所有路由组件都依靠BrowserRouter
为其提供浏览器HTML5历史记录API。
Note that React components have their first letter capitalized so as to identify them differently from default HTML tags.
请注意, React组件的首字母大写,以便与默认HTML标签区别对待。
The History API is an object that lets us manage the current location via history.location
as well as previous locations. Think of the location
property of the object as an array. The current location is the last item on the array and we manipulate the array through methods such as history.push()
orhistory.replace
. Whatever manipulation is made on the array will trigger a page transition to the current location. This is what happens behind the scene when using Link
and Redirect
components as we’ll see soon.
History API是一个对象,使我们可以通过history.location
和以前的位置来管理当前位置。 将对象的location
属性视为一个数组。 当前位置是数组上的最后一项,我们通过history.push()
或history.replace
方法操纵数组。 无论对数组进行任何操作,都将触发页面转换到当前位置。 这是使用Link
和Redirect
组件时在幕后发生的事情,我们将很快看到。
We’ve imported the contents of BrowserRouter
into the Router
variable. We need to wrap our entire app with it so it supplies the needed APIs all through the app. In App.js
add:
我们已经将BrowserRouter
的内容BrowserRouter
到Router
变量中。 我们需要用它包装整个应用程序,以便它在整个应用程序中提供所需的API。 在App.js
添加:
import React, { Component } from 'react';import '../styles/App.css';
// import route Components hereimport { BrowserRouter as Router, Route, Link, Switch, Redirect} from 'react-router-dom'
class App extends Component { render() { return ( <Router> <div className="App">
<div className="container"> <ul> <li><a href="">Hello</a></li> <li><a href="">About</a></li> <li><a href="">Books</a></li> </ul> <hr/>
{/* Routes will go here */}
</div> </div> </Router> ); }}
export default App;
<Route />组件 (The <Route /> component)
Lets begin exploring the Route
component. This component renders a page if the current URL location matches the path
prop specified in it. It also accepts component
, render
and children
props.
让我们开始探索Route
组件。 如果当前URL位置与其中指定的path
属性匹配,则此组件将呈现页面。 它也接受component
, render
和children
的道具。
Lets create ours where its written {/* Routes will go here */}:
让我们来创建我们的书面{/ *路线将在此处* /}的位置:
<Route path="/hello" component={Hello} /><Route path="/about" component={About} /><Route path="/books" component={Books} />
But those components don’t exist! Yes, you are right.
但是这些组件不存在! 是的,你是对的。
Again before we create them, lets add more imports to App.js
. Import from the HelloComponent.js
, AboutComponent.js
, and BooksComponent.js
using Hello
, About
, and Books
as variables. The component={}
prop uses curly braces to refer to variables not strings.
同样,在创建它们之前,让我们向App.js
添加更多导入。 使用Hello
, About
和Books
作为变量从HelloComponent.js
, AboutComponent.js
和BooksComponent.js
导入。 component={}
道具使用花括号来引用变量而不是字符串。
import React, { Component } from 'react';import '../styles/App.css';
import Hello from './HelloComponent';import About from './AboutComponent';import Books from './BooksComponent';
// import route Components hereimport { BrowserRouter as Router, Route, Link, Switch, Redirect} from 'react-router-dom'
Note that render
is similar to component={}
but it lets us define a component inline and right there:
请注意, render
与component={}
类似,但它使我们可以内联定义一个组件,并在此进行定义:
<Route path="/hello" render={() => { return ( <div className="jumbotron"> <h1 className="display-3">Hello, world!</h1> </div> ); }}/>
Head over to the empty HelloComponent.js
file and paste:
转到空的HelloComponent.js
文件并粘贴:
import React from 'react';
const Hello = () => { return ( <div className="jumbotron"> <h1 className="display-3">Hello, world!</h1> </div> );}
export default Hello;
We used a Stateless functional component (hence the arrow function) above. We use them for components that render only static content to a webpage as opposed to components that render stateful/changing content.
我们在上面使用了无状态功能组件(因此使用了箭头功能)。 我们将它们用于仅将静态内容呈现到网页的组件,而不是将有状态/更改内容呈现的组件。
If you didn’t notice, we are using Bootstrap 4 styles in our App.css
file hence the jumbotron
class in the div
.
如果您没有注意到,我们在App.css
文件中使用Bootstrap 4样式,因此在div
中使用了jumbotron
类。
// inside App.css. You'll need internet connection to load the Bootstrap 4 styles.
.App { padding-top: 50px;}
@import url('https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css');
Head over to the empty AboutComponent.js
file and paste:
转到空的AboutComponent.js
文件并粘贴:
import React from 'react';
const About = () => { return ( <div className="jumbotron"> <h1 className="display-3">About Me</h1> </div> );}
export default About;
Finally, head over to the empty BooksComponent.js
file and paste:
最后,转到空的BooksComponent.js
文件并粘贴:
import React from 'react';
const Books = () => { return ( <div className="jumbotron"> <h1 className="display-3">My Books</h1> </div> );}
export default Books;
One more thing we need to wrap up this section is the Link
component.
我们需要结束本节的另一件事是Link
组件。
<Link> </ Link&g t; 零件 (The <Link></Link> Component)
This is replaces the default <a href=""&g
t;</a> HTML tag. It acc
epts a to="" prop that points to the URL location we want to go to.
这将替换默认的<a href=""&g
t;</a> HTML标记。 我t acc
EPTS一到=“”托那个点我们想要去URL位置。
Inside App.js
, replace the default anchor tags with Link
:
在App.js
内部,将默认锚标记替换为Link
:
<ul> <li><Link to="/hello">Hello</Link></li> <li><Link to="/about">About</Link></li> <li><Link to="/books">Books</Link></li></ul>
Run npm start
from your terminal and see the complete app:
从终端运行npm start
并查看完整的应用程序:
How would you render a component if the /
URL is visited, such as the landing or home page. Your guess may be to create a route for it:
如果访问了/
URL(例如登录页面或主页),您将如何呈现组件。 您的猜测可能是为此创建一条路线:
<Route path="/" component={Home} />
This is fine but remember that the other paths have /
in them. So if we visited other URLs such as /hello
, /about
and /books
, theHome
component will keep being rendered by default. To fix this, write another prop exact
setting it to true
or just write exact
.
很好,但是请记住其他路径中有/
。 因此,如果我们访问了其他URL,例如/hello
, /about
和/books
,则默认情况下将继续呈现Home
组件。 要解决此问题,请编写另一个属性exact
将其设置为true
或者只编写exact
。
<Route path="/" exact={true} component={Home} />
This would ensure to Home
component is rendered only in cases where the URL is exactly matches this:/
.
这将确保仅在URL完全符合以下条件的情况下呈现Home
组件: /
。
Create a new HomeComponent.js
file in components/
folder. Paste this in:
在components/
创建一个新的HomeComponent.js
文件 夹。 将此粘贴到:
import React from 'react';
const Home = () => { return ( <div className="jumbotron"> <h1 className="display-3">Landing page</h1> </div> );}
export default Home;
Import into App.js
导入到App.js
import Home from './HomeComponent';
Add to the list of routes
添加到路线列表
<Route exact={true} path="/" component={Home} /><Route path="/hello" component={Hello} /><Route path="/about" component={About} /><Route path="/books" component={Books} />
Visit http://localhost:3000
and view:
访问http://localhost:3000
并查看:
Do some experiments. Remove exact={true}
from Home route and see what happens. You’ll see why its important.
做一些实验。 从本地路线中删除exact={true}
,然后看看会发生什么。 您会明白其重要性的原因。
<Switch> </ Switch>组件 (The <Switch></Switch> Component)
This will require being wrapped around Route
components when needed for implementation. When a URL path is visited, it allows only the first <Rou
te>that matches the path to be rendered.
在实现时,这将需要围绕Route
组件进行包装。 访问URL路径时,它仅允许显示与该路径匹配的第一个<Rou
te>。
Earlier we had an issue with /
rendering the Home
component and that of other paths. If we create a /hello/goodmorning
path, what will happen? The components of the /hello
and /hello/goodmorning
path will be rendered. Switch will help in this case again by choosing only one route to render but the most important route must be arranged to come first.
早些时候,我们在使用/
渲染Home
组件和其他路径时遇到了问题。 如果我们创建/hello/goodmorning
路径,将会发生什么? /hello
和/hello/goodmorning
路径的组件将被呈现。 在这种情况下,Switch仅会选择一条路径进行渲染,这将再次帮助您,但最重要的路径必须排在最前面。
Using Switch
, we can avoid what happens in the image above but only for URLs other than /
. exact={true}
handles it for /
. Remember that Switch
will pick only the first matching Route
. Lets put it to work and see the result.
使用Switch
,我们可以避免在上图中发生的情况,但仅针对/
以外的URL。 exact={true}
为/
处理它。 请记住, Switch
只选择第一个匹配的Route
。 让它发挥作用并查看结果。
<Switch> <Route exact path="/" component={Home} /> <Route path="/hello" component={Hello} /> <Route path="/hello/goodmorning" render={() => { return <h1>Goodmorning</h1> }} /> <Route path="/books" component={Books} /></Switch>
Furthermore, Switch
allows us to specify a route to render if the URL matches no location. For that route, leave the path
prop empty.
此外,如果URL不匹配任何位置, Switch
允许我们指定渲染路径。 对于该路线,将path
道具留空。
// Just an example. Don't implement. This catch-all Route would be at the bottom if implemented.
<Route component={NoMatch} />
In summary Switch
will do the following:
总之, Switch
将执行以下操作:
- avoid inclusive route rendering. 避免包含路径的渲染。
- include a catch-all Route at the bottom of our Switch container. 在我们的Switch容器的底部添加一个包罗万象的路线。
2嵌套路由 (2 Nested routing)
Remember that we could render components via Route
inline or by specifying the component:
请记住,我们可以通过内联Route
或通过指定组件来渲染组件:
<Route component={SomeComponent}/>
Or
要么
<Route render={() => { return <h1>Soemthing</h1> }/>
The component that will be created via Route
will automatically be passed the followingprop
objects:
将通过Route
创建的组件将自动传递以下prop
对象:
- match 比赛
- location 位置
- history 历史
We will only explore the use of match
as it is helpful for implementing nested routes. The match
object contains the following properties:
我们将仅探讨match
的使用,因为它有助于实现嵌套路由。 match
对象包含以下属性:
params — (object) Key/value pairs parsed from the URL corresponding to the dynamic segments of the path.
params —(对象)从URL解析的键/值对,对应于路径的动态段。
isExact — (boolean) true if the entire URL was matched (no trailing characters).
isExact —(布尔值)如果整个URL都匹配(没有结尾字符),则为true。
path — (string) The path pattern used to match. Useful for building nested <Route>s
path —(字符串)用于匹配的路径模式。 用于构建嵌套的<Route>
url — (string) The matched portion of the URL. Useful for building nested <Link>s
url —(字符串)URL的匹配部分。 对于构建嵌套的<Link>有用
We want to add new routes under the /book
route. They will be books:
我们要在/book
路由下添加新路由。 他们将是书:
- HTML HTML
- CSS CSS
- React React
Navigate to the second sub-folder 02-nested-routing
on your terminal and run npm install
.
导航到终端上的第二个子文件夹02-nested-routing
,然后运行npm install
。
In your code editor, open BookComponent.js
and modify:
在代码编辑器中,打开BookComponent.js
并修改:
const Books = ({ match }) => { return (<div> <div className="jumbotron"> <h1 className="display-3">My Books</h1> </div>
<div className="container"> <div className="row">
<div className="col-md-3"> <ul> <li><Link to="">HTML</Link></li> <li><Link to="">CSS</Link></li> <li><Link to="">React</Link></li> </ul> </div> <div className="col-md-9">
{/* place routes here */} </div> </div>
</div>
</div> );}
Lets install React Router via NPM. With the folder open in your terminal, run:
让我们通过NPM安装React Router。 在终端中打开文件夹的情况下,运行:
npm install react-router-dom
We’ve demonstrated syntactically that the match
object is passed as props
. Remember that the classes used are for Bootstrap’s styles to take effect. Don’t forget to import all React Router components after importing React:
我们已经在语法上证明了match
对象是作为props
传递的。 请记住,使用的类是使Bootstrap的样式生效的类。 导入React之后,不要忘记导入所有React Router组件:
import React from 'react';import { BrowserRouter as Router, Route, Link, Switch, Redirect } from 'react-router-dom';
We didn’t need to import all of them but we did anyway. Place the routes:
我们不需要全部导入,但是无论如何我们都做了。 放置路线:
<Route path="" render={() => { return <h1>HTML by Ducket book</h1> }}/><Route path="" render={() => { return <h1>CSS by Racheal Andrews</h1> }}/><Route path="" render={() => { return <h1>React by Fullstack.io book</h1> }}/>
We are using inline component rendering to save time. Now, lets populate the to=""
of Link
and path=""
of Route
.
我们使用嵌入式组件渲染来节省时间。 现在,让我们填充Link
的to=""
和Route
path=""
。
Make these changes:
进行以下更改:
<div className="col-md-3"> <ul> <li><Link to={`${match.url}/html`}>HTML</Link></li> <li><Link to={`${match.url}/css`}>CSS</Link></li> <li><Link to={`${match.url}/react`}>React</Link></li> </ul></div> <div className="col-md-9">
<Route path={`${match.path}/html`} render={() => { return <h1>HTML by Ducket book</h1> }}/> <Route path={`${match.path}/css`} render={() => { return <h1>CSS by Racheal Andrews</h1> }}/> <Route path={`${match.path}/react`} render={() => { return <h1>React by Fullstack.io book</h1> }}/>
</div>
${match.url}
evaluates to /books
and ${match.path}
evaluates to localhost://3000/books.
The back ticks used are ES6’s way of concatenating strings containing variables.
${match.url}
计算结果为/books
和${match.path}
计算结果为localhost://3000/books.
使用的反勾号是ES6连接包含变量的字符串的方式。
Give it a save, run npm start
and view the working app.
给它保存,运行npm start
并查看正在运行的应用程序。
3带有路径参数的嵌套路由 (3 Nested routing with path parameters)
Any URL that ends with /:id
,/:user
or /:whatever
indicates that that portion is a dynamically generated part of the URL that could be any value.
任何以/:id
, /:user
或/:whatever
结尾的URL表示该部分是URL的动态生成部分,可以是任何值。
We can access such portions via match.params.id
for use in routing.
我们可以通过match.params.id
访问这些部分以用于路由。
Again open the third sub-folder 03-nested-routing-with-path-parameters
in your terminal and run npm install
.
再次在终端中打开第三个子文件夹03-nested-routing-with-path-parameters
,然后运行npm install
。
Also, lets install React Router via NPM. With the folder open in your terminal, run:
另外,让我们通过NPM安装React Router。 在终端中打开文件夹的情况下,运行:
npm install react-router-dom
To illustrate the how path parameters can be used for routing, paste the following in Book.js
:
为了说明如何使用路径参数进行路由,请将以下内容粘贴到Book.js
:
import React from 'react';import { BrowserRouter as Router, Route, Link, Switch, Redirect } from 'react-router-dom';
const Books = ({ match }) => { return ( <div> <div className="jumbotron"> <h1 className="display-3">My Books</h1> </div>
<div className="container"> <div className="row"> <div className="col-md-3"> <ul> <li><Link to={`${match.url}/html`}>HTML</Link></li> <li><Link to={`${match.url}/css`}>CSS</Link></li> <li><Link to={`${match.url}/react`}>React</Link></li> </ul> </div> <div className="col-md-9"> <Route path={`${match.path}/html`} render={() => { return <h1>HTML by Ducket book</h1> }}/> <Route path={`${match.path}/css`} render={() => { return <h1>CSS by Racheal Andrews</h1> }}/> <Route path={`${match.path}/react`} render={() => { return <h1>React by Fullstack.io book</h1> }}/> <Route path={`${match.path}/:id`} component={Child} /> </div> </div> </div> </div> );}
const Child = ({ match }) => ( <div> <h3>URL ID parameter: {match.params.id}</h3> </div>);
export default Books;
Run npm start
.
运行npm start
。
4保护路径路由 (4 Protected path routing)
This kind of routing is for pages of a website that need the user to login and be authentication before viewing such pages. An example is an Admin page.
这种路由适用于网站的页面,需要用户在查看这些页面之前登录并进行身份验证。 一个例子是管理员 页。
To handle protected paths, we’ll need to use <Redirec
t/> (a standard component)and <Priva
teRoute/> (a custom component).
要处理受保护的路径,我们需要使用<Redirec
t />(一个标准组件t)and <Priva
teRoute />(一个自定义组件)。
<PrivateRout
e/> is not the standard &l
t;Route/> component. The standard route component provided by React Route
r is<Route/>;. We will defi
ne <PrivateRoute/> as
our own custom <Route/>.
<PrivateRout
e />不是ndard &l
路由组件。 由Rea的提供的标准路线分量ct Route
r是<路线/> ;. We will defi
;. We will defi
<PrivateRoute /> as
定义/> as
我们自己的自定义<Route />。
Custom routes are necessary when we need to make a decision whether a <Rout
e/> of interest should be rendered or not. As you’ll see in the code, we will list <Priva
teRoute/> together with ot
her <Route/>s.
当我们需要决定是否要显示感兴趣的<Rout
e />时,必须使用自定义路线。 正如您将在代码中看到的那样,我们将list <Priva
teRoute /> with ot
她的<Route />。
<Redirect />组件 (The <Redirect/> component)
Rendering a <Redirect> will navigate to a new location. The new location will override the current location in the history stack, like server-side redirects (HTTP 3xx) do.
渲染<Redirect>将导航到新位置。 新位置将覆盖历史记录堆栈中的当前位置,就像服务器端重定向(HTTP 3xx)一样。
<Redirec
t/> has a couple of props but we will be using
the to object prop this way:
<Redirec
吨/>有几个道具的,但我们将是全光照g
的反对道具这种方式:
<Redirect to={{ pathname: '/login', state: { from: props.location } }}/>
When used, this will redirect to the /login
path. Information about the last location before the redirect was done will be accessible by the LoginPage
component via this.props.location.state
.
使用时,它将重定向到/login
路径。 LoginPage
组件可以通过this.props.location.state
访问有关重定向完成之前的最后位置的信息。
Navigate to the last sub-folder 04-authenticated-routing
. Run npm install
.
导航到最后一个子文件夹04-authenticated-routing
。 运行npm install
。
Install React Router via NPM. With the folder open in your terminal, run:
通过NPM安装React Router。 在终端中打开文件夹的情况下,运行:
npm install react-router-dom
Open App.js
and add a new list /admin
item to the existing ones.
打开App.js
并将新的列表/admin
项添加到现有项。
<ul> <li><Link to="/hello">Hello</Link></li> <li><Link to="/about">About</Link></li> <li> <Link to="/books">Books</Link> </li> <li> <Link to="/admin">Admin</Link> </li></ul>
Add <PrivateRout
e/>; and
/login route to the group of existing &l
t;Route/>s.
添加<PrivateRout
e /> ; and
; and
/登录路由到该组的EXI sting &l
吨;路线/>秒。
<Switch> <Route exact path="/" component={Home} /> <Route path="/about" component={About} /> <Route path="/hello" component={Hello} /> <Route path="/books" component={Books} /> <Route path="/login" component={Login}/> <PrivateRoute authed={fakeAuth.isAuthenticated} path="/admin" component={Admin} /> </Switch>
Now create the <PrivateRout
e/> component outside
of App component:
现在创建<PrivateRout
E />部件outsi de
应用组件的:
const PrivateRoute = ({ component: Component, ...rest }) => ( <Route {...rest} render={props => ( fakeAuth.isAuthenticated ? ( <Component {...props}/> ) : ( <Redirect to={{ pathname: '/login', state: { from: props.location } }}/> ) )}/>)
<PrivateRout
e/> will eventually render down to a &
lt;Route> component.
The <Route> component uses a ternary operation to determine what to render based on whether the user is logged in or
not: a <Redirect/> to
the login page or Admin page component.
<PrivateRout
e />最终将渲染to a &
lt; Route> ponent.
在<路线>组件使用三元操作以确定基于用户是否为LO呈现什么gged in or
不:一个<重定向/&克t; to
t; to
登录页面或管理页面组件。
Create the Admin
component:
创建Admin
组件:
const Admin = () => { return ( <div className="jumbotron"> <h3 className="display-3">Admin Access granted</h3> </div> );}
Also, create the Login
component:
另外,创建Login
组件:
class Login extends React.Component { constructor() { super(); this.state = { redirectToReferrer: false } // binding 'this' this.login = this.login.bind(this); } login() { fakeAuth.authenticate(() => { this.setState({ redirectToReferrer: true }) }) } render() { const { from } = this.props.location.state || { from: { pathname: '/' } } const { redirectToReferrer } = this.state; if (redirectToReferrer) { return ( <Redirect to={from} /> ) } return ( <div className="jumbotron"> <h1 className="display-3">Login required</h1> <p className="lead">You must log in to view the page at {from.pathname}.</p> <p className="lead"> <a className="btn btn-primary btn-lg" onClick={this.login} role="button">Login</a> </p> </div> ) } } /* A fake authentication function */ export const fakeAuth = { isAuthenticated: false, authenticate(cb) { this.isAuthenticated = true setTimeout(cb, 100) }, }
This Login
component implements a fake authentication function that will set a user either logged in or out.
该Login
组件实现了伪造的身份验证功能,该功能将设置用户登录或注销。
Run npm start
and see the working app.
运行npm start
并查看正在运行的应用程序。
This brings us to the end of the article. Kudos to you if you made it this far. If you would like more details about React Router, view the Documentations.
这使我们到了本文的结尾。 如果您走了这么远,就对您表示敬意。 如果您想了解有关React Router的更多详细信息,请查看文档 。
If you would like the completed version of the code, visit the completed branch on Github.
如果您想要完整版的代码,请访问Github上完整的分支。
Feel free to support me (devapparel.co) and look good while at it. Also, Comment or Share this post. Thanks for reading!
随时支持我( devapparel.co ),并在此过程中表现出色。 另外,评论或分享此帖子。 谢谢阅读!
Originally published at Zeolearn Blog.
最初在Zeolearn博客上发布 。
翻译自: https://www.freecodecamp.org/news/beginners-guide-to-react-router-4-8959ceb3ad58/