目前主流项目方案 基本都是 采用SPA(单页应用)架构去做的 那么url 基本是基于hash去做路由的. 这种不存在兼容性问题
为了url 清爽干净的体验 可以替换成 history model 3大框架都有自己的配置方式 .如果基于react-router 4 可以使用 官方提供的browserHistory去做。
实现一个完整 history mode 需要以下步骤:
1. 指定 basename
可以在 BrowserRouter 中进行指定
<BrowserRouter basename="/webapp" />
为了在 非react组件中也能使用router 进行导航 推荐将router 封装一个服务,
BrowserRouter 和 router服务 选择其中一种即可.
router服务 : RouterHelper.js
import createHistory from 'history/createBrowserHistory';
export const history = createHistory(
{
// 基链接
basename: "/webapp",
}
);
这样在任意类中就可以引入router对象进行 路由导航,这种方式下basename指定需要在 createHistory中配置.
import {history} from "@common/class/RouterHelper";
在需要使用的类地方 可以导出使用。
一个完整的router服务的例子:
import {history} from "@common/class/RouterHelper";
const routes = [
{
path: "/account/user",
component: AccountManagerView,
meta : {title : "账户列表"},
},
{
path: "/account/userDetail",
component: AccountManagerDetailView,
meta : {title : "账户详情"},
},];
import { Router ,Route, withRouter, Switch } from 'react-router-dom'
<Router history={history}>
<Switch>
{
routes.map((route,i)=> <Route key={i} exact {...route} />)
}
<Route render={() => <h1 className={''}>找不到此页面</h1>} />
</Switch>
</Router>
ps : 注意使用router 服务方式 需要将history注入到 Router对象里面
2.nginx配置
将项目构建后 部署到nginx 静态服务器上面
服务器上文件夹为 : webapp
#webapp
location /webapp {
alias /home/static/webapp/;
index index.html;
try_files $uri /webapp/index.html;
}
alias 指定资源访问的目录
try_files 当前uri 如果未找到则重新定位到 /webapp/index.html下;