路由的兩種模式
history:hash | 不需要服務器支持 |
history:browser | react-router官方推薦,需要服務器支持(因爲是SPA項目,url切換時需要服務器始終返回index.html) |
由於hash不需要服務器支持,只需要放上去就ok了,不需要不過多的配置,就不多說了
此篇文章主要是記錄部署history:browser 模式的相關配置
使用create-react-app創建的項目相關代碼及配置
// package.json
"homepage":"http://a.yeashian.com/app"
// src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { BrowserRouter as Router } from 'react-router-dom'
import './assets/reset.css'
// 引入redux
import { Provider } from 'react-redux'
import store from './store'
ReactDOM.render(
<Provider store={store}>
<Router basename="/app/">
<App />
</Router>
</Provider>, document.getElementById('root'));
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
注意點:
代碼中加:
basename="/app/",這裏的 /app/ 和nginx中的location /app/ 一致
"homepage":"http://a.yeashian.com/app",此處爲域名(域名爲nginx中配置的),ip不行
跳轉不能使用window.location.href="xxxx",必須使用react路由跳轉
nginx中加:
location /app/ {
try_files $uri /app/index.html;
index index.html;
}