Preface:
Routing comes first, and was the first thing I wanted to understand when I started learning React. After all, there is only one front-end page we write. With the increase of business, or according to the UI design diagram, N pages drive the flow of N pages is < routing >. After all, many documents talk about front-end routing from its origins.
At least, after the routing understand, for the development of the page is certainly of great help. The React route is a route that can be routed using the react route. In terms of optimization, detailed adjustments will be made when the project is packaged.
For example, vue has a lazy load mode for routing. React must also have a lazy load mode.
A brief introduction to JSX syntax
First of all, we need to take a look at the official JSX documentation. The following is an excerpt from the official DOCUMENTATION
const element = <h1>Hello, world! </h1>;Copy the code
This interesting tag syntax is neither a string nor HTML.
It’s called JSX, and it’s a syntax extension to JavaScript. We recommend using JSX with React. JSX is a good way to describe how the UI should behave as it should interact. JSX may be reminiscent of a template language, but it has all the functionality of JavaScript.
JSX generates React “elements”.
JSX stands for object
Babel translates JSX into a function call called react.createElement ().
const element = (
<h1 className="greeting">
Hello, world!
</h1>
);Copy the code
const element = React.createElement( ‘h1’, {className: ‘greeting’}, ‘Hello, world!’ );
The above two pieces of code are exactly equivalent, which means that the above will compile into the following piece of code. Therefore, every page you write must incorporate React
import React from 'react'Meanwhile, react. createElement prechecks the code. If you've ever used Githook, you know that. Before we did vUE we introduced Husky and this was just to pre-check the code. 1. XXXX is defined but not used 2. === = instead of === instead of ==='logo'Is defined but never used no-unused-vars this requires you to pay attention to the quality of your code when writing it. Redundant or miswritten.Copy the code
React How to use routing
The react project does not have router files, so you can create a router folder /index.js to write routing files
This is what you can find in any related article. The next step is to interpret the code
React-router-dom
The first two sentences simply introduce the page component. If you’ve written about VUE and are familiar with VUE, this is not a problem. Even if you haven’t, it doesn’t matter.
Class home extends React.Component{}exportImport is used for imported components in default HomeCopy the code
You can check out the documentation for react-router-dom
www.jianshu.com/p/97e4af328…
React-router
React-router-dom
hashRouter
As the name implies, the path is marked with a #, which is the hash mode
The HashRouter component, which builds the route using window.location.hash and the hashchange event.
Link
Link component, which renders an A tag;
<Link to={your path}> </Link>Copy the code
Switch
Render the first
or
child that matches the path.
How is this different from just using a series of < routes >?
will render only one route. Instead, when just a series of < routes > are defined, each
that matches the path will be included in the render scope
<Route path="/home" component={home} /><Route path="/:value" component={value} />Copy the code
For the above code, if you access /home, it will all match. Which means these are all going to be rendered. What we want is the component rendering that corresponds to it. This is where the switch is needed.
Therefore, this author thinks that we can make it a convention to add switch to control our routingCopy the code
For details, please click the above link. The author’s article explains in detail.
See the code below for highlights
import Home from '.. /page/home/home'
import Article from '.. /page/article/article'
import React from 'react'
import { Route, Switch, HashRouter,withRouter } from 'react-router-dom'
class Router extends React.Component {
constructor(props) {
super(props)
this.state = {}
}
render() {
return (
<HashRouter>
<Switch>
<Route exact path="/" component={withRouter(Home)} />
<Route exact path="/article" component={Article} />
</Switch>
</HashRouter>
)
}
}
export default RouterCopy the code
Please take a closer look at this code with the screenshot above. There is one difference.
That’s right, withRouter. You probably don’t know what this is for. But you can certainly see it in other relevant articles. Now let’s look at withRouter in more detail
withRouter
WithRouter: Pass the history, location, and match objects of the react-router into the props object from components that are not switched over by route
React you can use this. Props to get routing parameters. When you print console output in your browser, you can see the following results.
But there is one case where you can’t get the props value. Chestnuts are given below
First I create a component which is the header component and I write it in the component in the directory I sorted out earlier
Next we’ll introduce app.js
import React from 'react'; import'./App.css';
import Router from './router/index'
import Headers from './component/header/index';
function App() {
return (
<div className="App">
<Headers />
<Router />
</div>
)
}
export default App;Copy the code
In the header component, I output props to run the project. You’ll find that the props controlling the output is empty.
I’m going to have to put N tags in the header to control the page. Dynamic styling of tags is a natural addition.
Although window.location can be used to monitor route changes, I am obsessive-compulsive. Since I need to learn React, I would definitely like to use react syntax to solve the problem. So there’s a concept involved here:
By default, the component must be routing-matched to have this. Props. To have route parameters, use programmatic navigation to write this.'/detail') To the page of the routeCopy the code
The header is a common component, not a component that matches the rendering with routing controls, so the props is empty. So? One solution provided by the react-router-dom is the withRouter
The role of the withRouter is described at the beginning
So, change the header page
import React from 'react'
import {withRouter} from 'react-router-dom'WithRouter class Headers extends React.Component{getProps() {
console.log(this.props)
console.log(window.location)
}
render() {
return(<div> this is the header {this.getprops ()}</div>)}}export default withRouter(Headers)Copy the code
Run the project, ???? Direct error
Error: Invariant failed: You should not use <withRouter(Headers) /> outside a <Router>Copy the code
Then it becomes clear that the withRouter will write inside the router tag pair. However, it is a common component and cannot be written in the routing configuration file. Is there a way to accommodate both?
Concept: slot
If you’ve ever used VUE, you’re familiar with slots. What is it for? It’s simple. It’s a customizable component that can render anything you write. The way to do this is with
Vue slots will not be explained in detail in this article and will be interpreted separately in subsequent articles.
React doesn’t have a socket concept, but it does provide a syntax: this.props. Children
See the following example:
class RootContent extends React.Component{
constructor(props){
super(props);
}
render() {return (
<div className='divider'>
{this.props.children}
</div>
);
}
}
class RootChild extends React.Component{
constructor(props){
super(props);
}
render() {return (
<RootContent>
<p>Hello, React</p>
<p>Hello, Redux</p>
<p>Hello, Facebook</p>
<p>Hello, Google</p>
</RootContent>
);
}
}
ReactDOM.render(
<RootChild />,
document.querySelector('#root')); This case from "https://www.jianshu.com/p/ea4eaf32cd46 "For the sake of time, I use the ellipsis to illustrate the case of othersCopy the code
In accordance with this, I made some adjustments to my project. The following is only an excerpt of the modified files
The author makes a brief introduction:
// app.js
import React from "react"; import"./App.css"; import PropTypes from"prop-types"; import routers from"./router/router.js"; import { HashRouter, Route, Switch } from"react-router-dom"; import Layout from"./component/layout/layout.js"; const App = () => {return(<HashRouter> <main> <Switch> <Layout> /* React loop render available */ {routers. Map ((item, index) => {return( <Route path={item.path} exact={item.exact} component={item.component} key={index} /> ); })} </Layout> </Switch> </main> </HashRouter> ); };export default App;Copy the code
The following code is taken from router/index.js
import Home from ".. /page/home/home.js"; import Articles from".. /page/article/article.js"; import ArticleDetail from".. /page/articleDetail/articleDetail"; const config = [ { path:"/", component: Home, exact: true, }, { path: "/articles", component: Articles, exact: true, }, { path: "/article/detail/:value", component: ArticleDetail, exact: true, },];// class RouteMap extends React.Component {// render() {/ /return (// <HashRouter>// <main>// <Switch>// <Route path="/" exact component={Home} />// <Route path="/home" exact component={Home} />// <Route path="/article" exact component={Articles}></Route>// </Switch>// </main>// </HashRouter>// )// }// }exportdefault config; In this way, the route configuration page is all about defining routes, as you'll know if you've written vUE. Vue is something like thisCopy the code
Here is an excerpt of layout
import React from "react"; import"./index.scss"; import Header from".. /header/index"; class Layout extends React.Component {render() { return ( <div className="home"> <div className="header"> <Header /> </div> <div className="main"> <div className="co">
/* this.props.children */ {this.props.children} </div> </div> </div> ); }}export default Layout;Copy the code
Once you’re done, you can continue running the project, and you can get the props value in the header. You can then listen on the route to customize the dynamic style of the header tag.
The author’s ideas:
I decided to write a layout for this.props. Children. This component consists of two modules: header and content.
And the content is dynamically rendered with route matching, but you can’t write much if the page grows too much later
<route> tag. The React loop was used to adjust the route. In this way, the original routing file is really just a route definition. ,
At this point, the routing is preliminarily configured, and the problem that non-routing matching components cannot obtain props is solved
Finally, the author also started to write, the writing level is not very good. Forgive me. If you think it will help you, please give it a star. ,
Github.com/luoying122/…
Projects are constantly written and updated. Wait until the front-end and back-end services are complete and the deployment goes online. This project is my personal technology blog. Looking forward to the completion of public network access to the day, is willing to share with you