为什么我无法使用反应路由器路由我的应用程序?

时间:2017-03-17 10:04:17

标签: javascript reactjs react-router

我开始通过制作基本应用程序来学习React和React路由器,但是我收到警告我无法解决

Warning 1: React.createElement: type is invalid -- expected a string 
(for built-in components) or a class/function (for composite components)
but got: undefined.

Warning 2: Failed prop type: The prop `history` is marked as required
in `Router`, but its value is `undefined`.

我的代码:

index.js

import React from 'react'
import ReactDOM from 'react-dom'
import routes from './routes'

ReactDOM.render(routes, document.getElementById('app'));

routes.js

import React from 'react'
import { Route } from 'react-router'
import Home from './components/home';
import Login from './components/login'
const routes = (
  <Route path="/" component={Home}>
     <Route path="/login" component={Login} />

  </Route>
);

export default routes;

。     home.js

import React from 'react'

export default React.createClass({
  render(){
      return (
          <div>
              <h1>Hello From Home</h1>
          </div>);
  }
});

login.js

import React from 'react'


export default React.createClass({
  render(){
    return (<h1>Hello From Login Page</h1>);
  }
});

这是我的

的package.json

{
  "name": "basicapp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {

    "production": "webpack -p",
    "start": "webpack-dev-server"
  },
  "author": "aviaTorX",
  "license": "ISC",
  "dependencies": {
   "react": "^15.4.2",
   "react-dom": "^15.4.2",
   "react-router": "^4.0.0"
 },
 "devDependencies": {
    "babel-core": "^6.24.0",
    "babel-loader": "^6.4.0",
     "babel-preset-react": "^6.23.0",
    "html-webpack-plugin": "^2.28.0",
    "webpack": "^2.2.1",
    "webpack-dev-server": "^2.4.2"
 }
}

上面提到的警告是空白屏幕。

3 个答案:

答案 0 :(得分:0)

如果您正在使用react-router ^4.0.0,那么您的根组件需要 一个Router元素。您的routes.js文件似乎遗漏了。 您的routes.js应如下所示:

import React from 'react'
import { Route, BrowserRouter as Router } from 'react-router'
import Home from './components/home';
import Login from './components/login'
const routes = (
  <Router>
    <Route path="/" component={Home}>
      <Route path="/login" component={Login} />
    </Route>
  </Router>
);

export default routes;

答案 1 :(得分:0)

您的routes.js应该是

    import React     from 'react'
    import { 
        Route,
        Router,
        IndexRoute,
        hashHistory
    }                from 'react-router'
    import Home      from './components/home';
    import Login     from './components/login'

    export const routes = () => {
        return(  
           <Router history={hashHistory}>
             <IndexRoute component={Home} />
             <Route path="/login" component={Login} />
           </Router>
        );
    };
    export default routes;

答案 2 :(得分:0)

您可以直接使用this.props.history.push('/list/')。 但请记住,react-router的版本为^4.2.0