我一直在跟随Tyler Mcginnis的教程,并对反应路由器,特别是与历史记录有关.我最后逐字复制他的代码只是为了看看它是否只有我,但我还是得到了
Warning: React.createElement: type is invalid -- expected a string (for built- in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in. Warning: Failed prop type: The prop `history` is marked as required in `Router`,but its value is `undefined`. in Router Uncaught TypeError: Cannot read property 'location' of undefined at new Router (index_bundle.js:8347) at index_bundle.js:19079 at measureLifeCyclePerf (index_bundle.js:18859) at ReactCompositeComponentWrapper._constructComponentWithoutOwner (index_bundle.js:19078) at ReactCompositeComponentWrapper._constructComponent (index_bundle.js:19064) at ReactCompositeComponentWrapper.mountComponent (index_bundle.js:18972) at Object.mountComponent (index_bundle.js:4070) at ReactCompositeComponentWrapper.performInitialMount (index_bundle.js:19155) at ReactCompositeComponentWrapper.mountComponent (index_bundle.js:19042) at Object.mountComponent (index_bundle.js:4070)
实施是:
var React = require('react'); var ReactRouter = require('react-router'); var Router = ReactRouter.Router; var Route = ReactRouter.Route; var hashHistory = ReactRouter.hashHistory; var IndexRoute = ReactRouter.IndexRoute; var Main = require('../components/Main'); var Home = require("../components/Home"); var PromptContainer = require('../containers/PromptContainer'); var routes = ( <Router history={hashHistory}> <Route path='/' component={Main}> <IndexRoute component={Home} /> <Route path='playerOne' header='Player One' component={PromptContainer} /> <Route path='playerTwo/:playerOne' header='Player Two' component={PromptContainer} /> </Route> </Router> ); module.exports = routes;
我注意到的是,react-path模块中不存在hashHistory,而是在历史模块中有一个createBrowserHistory.按照我发现的API文档,我想我必须通过那里调用它:
var BrowserHistory = require('history/createBrowserHistory); const history = createBrowserHistory();
这样做会产生一个createBrowserHistory不是函数错误.删除paranthesis,导致上述相同的错误,说明历史记录是未定义的.
当我记录历史时,它肯定是未定义的,这让我相信这个问题与import语句有关,但是控制台不会告诉我无法找到ReactRouter.hashHistory吗?
我理解这个教程已经有一年了,我可能没有注意到API的变化,这就是我的问题所在.任何帮助表示赞赏!
路由器v4有点不同
HashHistory
import { HashRouter as Router,Route } from 'react-router-dom'; import App from './components/App'; render(( <Router> <Route exact path="/" component={App} /> </Router> ),document.getElementById('root'));
或BrowserHistory
import { BrowserRouter as Router,document.getElementById('root'));