React 路由器显示空白页面

问题描述 投票:0回答:4

我正在尝试开始使用 react-router。

import React from 'react';
import ReactDOM from 'react-dom';
import HelloWorld from './pages/HelloWorld';
import {Router, Route, IndexRoute, hashHistory,browserHistory} from "react-router";
...
const app = document.getElementById('root')
ReactDOM.render(<HelloWorld/>, app);

这里是虚拟类 HelloWorld:

import React, { Component } from 'react';

class HelloWorld extends Component {
  render(){
      return(<h1> HelloWorld </h1>);
  }
}

export default HelloWorld;

使用此设置一切正常。但是,使用路线我最终得到一个空白页面。

ReactDOM.render(
<Router history = {hashHistory}>
    <Route path ="/" component={HelloWorld}>
    </Route>
</Router>,
app);

错在哪里?我搜索了 stackoverflow,但似乎没有合适的答案。

对我来说真正奇怪的是,以下代码也会导致空白页:

const Routes = () => (
  <Router history = {browserHistory}>
    <Route path ="/" render={ () => (<h1> HelloWorld </h1>) } />
  </Router>
);
const app = document.getElementById('app')
ReactDOM.render(<Routes/>, app);
node.js reactjs react-router create-react-app
4个回答
1
投票

您正在以 V3 方式使用 V4。

代替

import {Router, Route, IndexRoute, hashHistory,browserHistory} from "react-router";

这样导入依赖:

import {BrowserRouter as Router, Route} from "react-router";
import createHistory from "history/createBrowserHistory"  // browser history moved into a standalone package since v4.

0
投票

好的“一个”解决方案是:

import {BrowserRouter as Router, Route, IndexRoute,hashHistory,browserHistory} from "react-router-dom";
...
const Routes = () => (
   <Router history = {browserHistory}>
    <Route path ='/' component={ Layout } />
   </Router>
);

const app = document.getElementById('app')
ReactDOM.render(<Routes/>, app);

0
投票

99% 确定您的问题是您的标签具有相对链接。让它绝对。

<!-- do this -->
<script src="/static/bundle.js"></script>
<!-- not -->
<script src="static/bundle.js"></script>
<!-- or -->
<script src="./static/bundle.js"></script

0
投票

使用这种类型只需点击两页

import{ BrowserRouter as Router,Route,Routes}  from 'react-router-dom'

  
function App() {
const [page, setPage] = useState('');

return (
<div className="App">
  
  <button onClick={() => setPage("about")}>to scold</button>
  <button onClick={()=>setPage('hello')}>to hello</button>
  <Router>
    <Routes>
    <Route element= {<Hello/>} path="/hello"/>
    </Routes>
 
  </Router>
</div>
);

}

© www.soinside.com 2019 - 2024. All rights reserved.