2017-04-13 87 views
0

我正在嘗試使用react-router-dom 4,但無法直接導航到路由。react-router-dom 4路由問題

這裏是我的代碼示例:

let Test = (props) => (<div>This is a test component</div>); 
 
let About = (props) => (<div>About us</div>); 
 

 
class App extends Component { 
 
    render() { 
 
    return (
 
     <Router> 
 
     <div> 
 
      <nav> 
 
      <NavLink to="/about" activeClassName="selected">About</NavLink> 
 
      <NavLink to="/" activeClassName="selected">Test</NavLink> 
 
      </nav> 
 
      <Route exact path="/" component={Test} /> 
 
      <Route exact path="/about" component={About} /> 
 
     </div> 
 
     </Router> 
 
    ) 
 
    } 
 
}

當我嘗試只是去localhost:3000/about,我得到在瀏覽器中未找到。但是當我去localhost:3000,然後點擊關於鏈接,我重定向就好了。

在我的控制檯,我得到

Uncaught Error: uBlock Origin: aborting content scripts for http://localhost:3000/about at contentscript.js:90

+0

你可以在[真實世界的React App這裏]看到這個工作(https://github.com/ModusCreateOrg/budgeting-sample -app-webpack2) – Grgur

回答

2

我假設你正在使用的WebPack。如果是這樣,在你的webpack配置中添加一些東西應該可以解決問題。具體而言,output.publicPath = '/'devServer.historyApiFallback = true。下面是一個webpack配置的例子,它使用了^和修復了刷新問題。如果你很好奇「爲什麼」,this將會有所幫助。

當你去到本地主機
var path = require('path'); 
var HtmlWebpackPlugin = require('html-webpack-plugin'); 

module.exports = { 
    entry: './app/index.js', 
    output: { 
    path: path.resolve(__dirname, 'dist'), 
    filename: 'index_bundle.js', 
    publicPath: '/' 
    }, 
    module: { 
    rules: [ 
     { test: /\.(js)$/, use: 'babel-loader' }, 
     { test: /\.css$/, use: [ 'style-loader', 'css-loader' ]} 
    ] 
    }, 
    devServer: { 
    historyApiFallback: true, 
    }, 
    plugins: [ 
    new HtmlWebpackPlugin({ 
     template: 'app/index.html' 
    }) 
    ] 
}; 
+1

謝謝泰勒!那個鏈接正是我想要弄清楚發生了什麼的。我的測試服務器正在運行_serve_,它似乎沒有配置文件。我只是拋棄_webpack-dev-server_。 – gerald

+0

不用擔心。很高興你有它的工作。 –

0

:3000 /約,它的運行服務器端的路線,而你沒有設置服務器端的路線,這樣你就得到了404;當你去只是本地主機:3000,然後點擊關於鏈接,現在,您運行您設置的客戶端路線。換句話說,它運行react-router-dom,所以你可以得到頁面