我一直在关注 Tyler Mcginnis 的教程,并在 React 路由器上遇到了障碍,特别是历史。我最终逐字复制了他的代码只是为了看看它是否只有我,但我仍然得到
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;
我注意到modulehashHistory
中不存在react-router
,而是modulecreateBrowserHistory
内部有一个history
。按照我找到的 API 文档,我想我必须通过以下方式调用它:
var BrowserHistory = require('history/createBrowserHistory);
const history = createBrowserHistory();
这样做会产生createBrowserHistory is not a function
错误。删除括号,会导致上面说明 history is 的相同错误undefined
。
当我记录历史时,它肯定是未定义的,这让我相信问题与导入语句有关,但控制台不会告诉我ReactRouter.hashHistory
找不到吗?
我知道这个教程已经有一年了,我可能不知道 API 发生了变化,这就是我的问题所在。任何帮助表示赞赏!