By Webpack, the entire react project can be integrated into a single-page Web site, where routing can be handled through React-router.
Install First:
NPM Install React-router--save
Because React-router uses history, it is necessary to configure it in Webpack.config.js:
Devserver: {
Historyapifallback:true
}
Otherwise, a URL like localhost:8080/foo will return 404. After that, in order to make the whole project a single page, do the following:
Import {Router, browserhistory} from ' React-router ';
Export default class APP extends React.component
{
Routes = {
Path: '/',
Indexroute: {
OnEnter: (nextstate, replace) = {},
},
childroutes:[
]
}
Render () {
Return <router history={browserhistory} routes={this.routes}/>
}
}
The routes configuration can be found on the GitHub page of React-router. At the same time, you need to configure the appropriate route for other components, which are written in routes.childroutes.
Because a large number of components need to set the route, this can be seen as a common feature of the component class, you can use decorator to make the code more concise, decorator details can be found, but in order to use it, you must first install the corresponding Babel plug-in:
NPM Install Babel-plugin-transform-decorators-legacy--save, at the same time, needs to be configured in the plugins in. BABELRC:
"Plugins": [
"Transform-class-properties",
"Babel-plugin-transform-decorators-legacy"
],
Here we define a function Reactcomponentex, use it to return a decorator function, and in the function of the class to do the corresponding processing, mainly configuration react-router:
Export default function Reactcomponentex (path) {
return function (target, property, descriptor) {
Class _target extends target{
Static route = {
Path:path,
Component:_target,
indexroute:{},
ChildRoutes:target.childRoutes && Target.childRoutes.map (v=>{
return {
Path:v.path,
Component:v.component
}
})
}
};
return _target;
}
}
At this point, you can write this function at the outermost of each react component that you want to set the route to, such as:
@reactComponentEx (' foo ')
Export default class Foo extends react.component{...
And then configure it to the total route just now:
Routes = {
Path: '/',
Indexroute: {
OnEnter: (nextstate, replace) = {},
},
childroutes:[
Require ("foo"). Default.route//Through decorator has produced this route
]
}
You can access the corresponding page in the form of Localhost:8080/foo.
TCG Development Log (5) Decorator, React-router