反应路由器实施

React Router implementation

我是 ReactJS 的新手,我正在学习如何使用 react-router 进行路由,但是 react-router documentation 只是我沮丧的根源,所以我必须去其他地方去理解它。

这是我的代码:

ReactDOM.render((
        <ReactRouter>
            <ReactRouter.Route path="/" component={App}>
                <ReactRouter.Route path="create" component={CreateRecipe} />
                <ReactRouter.Route path=":id" component={ShowRecipe}>
                    <ReactRouter.Route path="edit" component={EditRecipe} />
                    <ReactRouter.Route path="delete" component={DeleteRecipe} />
                </ReactRouter.Route>
            </ReactRouter.Route>
        </ReactRouter>
    ), document.getElementById("app-container"));

但是在浏览器上加载时,我在浏览器的控制台中收到以下错误。

Warning: React.createElement: type should not be null, undefined, boolean, or number. It should be a string (for DOM elements) or a ReactClass (for composite components).

请问可能是什么原因,我该如何解决?

您的路由应包含在路由器内,因此 <ReactRouter> 应为 <ReactRouter.Router>

ReactDOM.render((
    <ReactRouter.Router>
        <ReactRouter.Route path="/" component={App}>
            <ReactRouter.Route path="create" component={CreateRecipe} />
            <ReactRouter.Route path=":id" component={ShowRecipe}>
                <ReactRouter.Route path="edit" component={EditRecipe} />
                <ReactRouter.Route path="delete" component={DeleteRecipe} />
            </ReactRouter.Route>
        </ReactRouter.Route>
    </ReactRouter.Router>
), document.getElementById("app-container"));

如果您想清理代码,可以将所有 ReactRouter.Router 替换为 Router,将 ReactRouter.Route 替换为 Route,然后调整您的代码:

var Router = ReactRouter.Router;  
var Route = ReactRouter.Route;

如果您正在努力阅读文档以了解可以使用 react-router 和一些示例做什么,我建议您观看 this video from Michael Jackson