【问题标题】:React router shows blank pageReact路由器显示空白页面
【发布时间】:2018-02-16 04:39:06
【问题描述】:

我正在尝试开始使用 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);

【问题讨论】:

  • 您正在导出Featured,但您的课程名为HelloWorld
  • 如果@Chris 建议的只是一个错字并且不在您的实际代码中,那么我们需要知道您使用的是哪个版本的 React-router
  • 嗨,我正在使用 v 4.1.2 ( react-router": "^4.1.2)。是的,错误的导出只是一个错字!
  • 您可以尝试将&lt;Route path ="/" component={HelloWorld}&gt; &lt;/Route&gt; 更新为&lt;Route path="/" component={HelloWorld}&gt; &lt;IndexRoute component={HelloWorld}/&gt; &lt;/Route&gt;
  • 嘿,这些更改也会导致空白页

标签: node.js reactjs react-router create-react-app


【解决方案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.

【讨论】:

  • 仍然是空白页
【解决方案2】:

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

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);

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-20
      • 2022-03-23
      • 1970-01-01
      • 2022-06-25
      • 2016-11-24
      • 2019-09-23
      • 1970-01-01
      相关资源
      最近更新 更多