دليل كامل للمبتدئين لتفاعل جهاز التوجيه (بما في ذلك خطافات جهاز التوجيه)

React هي مكتبة JavaScript لبناء واجهات المستخدم. يمكننا أيضًا توسيعه لإنشاء تطبيقات متعددة الصفحات بمساعدة React Router. هذه مكتبة تابعة لجهة خارجية تتيح التوجيه في تطبيقات React الخاصة بنا.

في هذا البرنامج التعليمي ، سنغطي كل ما تحتاج إلى معرفته لبدء استخدام React Router.

  • اقامة المشروع
  • ما هو التوجيه؟
  • إعداد جهاز التوجيه
  • طرق التقديم
  • استخدام الروابط للتبديل بين الصفحات
  • اجتياز معلمات المسار
  • التنقل برمجيًا
  • إعادة التوجيه إلى صفحة أخرى
  • إعادة التوجيه إلى صفحة 404
  • طرق حراسة
  • خطاف جهاز التوجيه
  • useHistory
  • useParams
  • useLocation
  • افكار اخيرة
  • الخطوات التالية

اقامة المشروع

لتتمكن من المتابعة ، ستحتاج إلى إنشاء تطبيق React جديد عن طريق تشغيل الأمر التالي في جهازك:

npx create-react-app react-router-guide 

بعد ذلك ، أضف سطور التعليمات البرمجية هذه إلى App.jsالملف:

import React from "react"; import "./index.css" export default function App() { return (   
    
  • Home
  • About
  • Contact
); } // Home Page const Home = () => (

Home

); // About Page const About = () => (

About

); // Contact Page const Contact = () => (

Contact

); const FakeText = () => (

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

)

بعد ذلك ، إذا كنت مستعدًا للانطلاق ، فلنبدأ بالإجابة على سؤال مهم: ما هو التوجيه؟

ما هو التوجيه؟

التوجيه هو القدرة على إظهار صفحات مختلفة للمستخدم. هذا يعني أنه يمكن للمستخدم التنقل بين أجزاء مختلفة من التطبيق عن طريق إدخال عنوان URL أو النقر فوق عنصر.

كما تعلم بالفعل ، تأتي React افتراضيًا بدون توجيه. ولتمكينه في مشروعنا ، نحتاج إلى إضافة مكتبة تسمى جهاز التوجيه التفاعلي.

لتثبيته ، سيتعين عليك تشغيل الأمر التالي في جهازك الطرفي:

yarn add react-router-dom 

أو

npm install react-router-dom 

الآن ، لقد نجحنا في تثبيت جهاز التوجيه الخاص بنا ، فلنبدأ في استخدامه في القسم التالي.

فرح

إعداد جهاز التوجيه

لتمكين التوجيه في تطبيق React الخاص بنا ، نحتاج أولاً إلى الاستيراد BrowserRouterمن react-router-dom.

في App.jsالملف ، أدخل ما يلي:

import React, { Fragment } from "react"; import "./index.css" import { BrowserRouter as Router } from "react-router-dom"; export default function App() { return (    
    
  • Home
  • About
  • Contact
); }

This should hold everything in our app where routing is needed. That means, if we need routing in our entire app, we must wrap our higher component with BrowserRouter.

By the way, you don't have to rename BrowserRouter as Router as I do here, I just want to keep things readable.

A router alone doesn't do much. So let's add a route in the next section.

Rendering routes

To render routes, we have to import the Route component from the router package.

In your App.js file, add the following code:

import React, { Fragment } from "react"; import "./index.css" import { BrowserRouter as Router, Route } from "react-router-dom"; export default function App() { return (    
    
  • Home
  • About
  • Contact

Welcome!

} /> ); }

Then, add it where we want to render the content. The Route component has several properties. But here, we just need path and render.

path: the path of the route. Here, we use / to define the path of the home page.

render: will display the content whenever the route is reached. Here, we'll render a welcome message to the user.

In some cases serving routes like that is perfectly fine. But imagine a case when we have to deal with a real component – using render may not be the right solution.

So, how can we display a real component? Well, the Route component has another property named component.

Let's update our example a bit to see it in action.

In your App.js file, add the following code:

import React, { Fragment } from "react"; import "./index.css" import { BrowserRouter as Router, Route } from "react-router-dom"; export default function App() { return (    
    
  • Home
  • About
  • Contact
); } const Home = () => (

Home

);

Now, instead of rendering a message, our route will load the Home component.

To get the full power of React Router, we need to have multiple pages and links to play with. We already have pages (components if you want, too), so now let's add some links so we can switch between pages.

Using links to switch pages

To add links to our project, we will use the React Router again.

In your App.js file, add the following code:

import React, { Fragment } from "react"; import "./index.css" import { BrowserRouter as Router, Route, Link } from "react-router-dom"; export default function App() { return (    
    
  • Home
  • About
  • Contact
); } const Home = () => (

Home

); const About = () => (

About

); const Contact = () => (

Contact

);

After importing Link, we have to update our navigation bar a bit. Now, instead of using a tag and href, React Router uses Link and to to, well, be able to switch between pages without reloading it.

Then, we need to add two new routes, About and Contact, to be able to switch between pages or components.

Now, we can go to different parts of our app through links. But there is an issue with our router: the Home component is always displayed even if we switch to other pages.

This is because React Router will check if the path defined starts with /. If that's the case, it will render the component. And here, our first route starts with /, so the Home component will be rendered each time.

However, we can still change the default behavior by adding the exact property to Route.

In App.js, add:

By updating the Home route with exact, now it will be rendered only if it matches the full path.

We can still enhance it by wrapping our routes with Switch to tell to React Router to load only one route at a time.

In App.js, add:

import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom";      

Now that we have new links, let's use them to pass parameters.

Passing route parameters

To pass data between pages, we have to update our example.

In your App.js file, add the following code:

import React, { Fragment } from "react"; import "./index.css" import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom"; export default function App() { const name = 'John Doe' return (    
    
  • Home
  • About
  • Contact
); } const Home = () => (

Home

); const About = ({match:{params:{name}}}) => ( // props.match.params.name

About {name}

); const Contact = () => (

Contact

);

As you can see here, we start by declaring a new constant name which will be passed as a parameter to the About page. And we append name to the corresponding link.

With that, we now have to update the About route by adjusting its path to receive name as a parameter path="/about/:name".

Now, the parameter will be received as props from the About component. The only thing we have to do now is destructure the props and get back the name property. By the way, {match:{params:{name}}} is the same as props.match.params.name.

We've done a lot up to this point. But in some cases we don't want to use links to navigate between pages.

Sometimes, we have to wait for an operation to finish before navigating to the next page.

يوافق على

So, let's handle that case in the next section.

Navigating programmatically

The props we receive have some convenient methods we can use to navigate between pages.

In App.js, add:

const Contact = ({history}) => (  

Contact

history.push('/') } >Go to home );

Here, we pull the history object from the props we receive. It has some handy methods like goBack, goForward, and so on. But here, we will use the push method to be able to go to the Home page.

Now, let's handle the case when we want to redirect our user after an action.

Redirecting to another page

The React Router has another component named Redirect. As you guessed, it helps us redirect the user to another page

In App.js, add:

import { BrowserRouter as Router, Route, Link, Switch, Redirect } from "react-router-dom"; const About = ({match:{params:{name}}}) => ( // props.match.params.name  { name !== 'John Doe' ?  : null } 

About {name}

);

Now, if the name passed as a parameter is not equal to John Doe, the user will be redirected to the home page.

You could argue that you should redirect the user with props.history.push('/). Well, the Redirect component replaces the page and therefore the user can't go back to the previous page. But, with the push method they can. However, you can use props.history.replace('/) to mimic the Redirect behavior.

Now let's move on and handle the case when the user hits a route that doesn't exist.

Redirecting to a 404 page

To redirect the user to a 404 page, you can create a component to show it. But here, to keep things simple, I will just display a message with render.

import React, { Fragment } from "react"; import "./index.css" import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom"; export default function App() { const name = 'John Doe' return (    
    
  • Home
  • About
  • Contact

404: page not found

} /> ); }

The new route we've added will catch every path that doesn't exist and redirect the user to the 404 page.

Now, let's move on and learn how to protect our routes in the next section.

Guarding routes

There are many ways to protect routes to React. But here I will just check if the user is authenticated and redirect them to the appropriate page.

import React, { Fragment } from "react"; import "./index.css" import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom"; export default function App() { const name = 'John Doe' const isAuthenticated = false return (    
    
  • Home
  • About
  • Contact
{ isAuthenticated ? : } ); }

As you can see here, I declared a variable to mimic authentication. Then, check if the user is authenticated or not. If they are, render protected pages. Otherwise redirect them to the home page.

We've covered a lot up to this point, but an interesting part remains: router hooks.

Let's move to the final section and introduce Hooks.

نعم

Router Hooks

Router hooks make things much easier. Now you can access the history, location, or parameters in an easy and elegant way.

useHistory

The useHistory hook gives us access to the history instance without pulling it from props.

import { useHistory } from "react-router-dom"; const Contact = () => { const history = useHistory(); return (  

Contact

history.push('/') } >Go to home ) };

useParams

This hook helps us get the parameter passed on the URL without using the props object.

import { BrowserRouter as Router, Route, Link, Switch, useParams } from "react-router-dom"; export default function App() { const name = 'John Doe' return (    
    
  • Home
  • About
); } const About = () => { const { name } = useParams() return ( // props.match.params.name { name !== 'John Doe' ? : null }

About {name}

) };

useLocation

يقوم هذا الخطاف بإرجاع كائن الموقع الذي يمثل عنوان URL الحالي.

import { useLocation } from "react-router-dom"; const Contact = () => { const { pathname } = useLocation(); return (  

Contact

Current URL: {pathname}

) };

افكار اخيرة

React Router هي مكتبة رائعة تساعدنا في الانتقال من صفحة واحدة إلى تطبيق متعدد الصفحات مع سهولة الاستخدام. (فقط ضع في اعتبارك - في نهاية اليوم ، لا يزال التطبيق عبارة عن صفحة واحدة).

والآن مع خطافات جهاز التوجيه ، يمكنك أن ترى مدى سهولة وأناقة هذه الأشياء. إنها بالتأكيد شيء يجب مراعاته في مشروعك القادم.

يمكنك قراءة المزيد من مقالاتي على مدونتي.

الخطوات التالية

رد فعل وثائق جهاز التوجيه

تصوير جوشوا سورتينو على Unsplash