React Router报错:不应在Router外部使用Route组件
Hey there! I've run into this exact snag before, so let me walk you through fixing it quickly.
The error message is pretty clear—all <Route> components (and any routing-related elements like <Link>) need to be wrapped inside a router component from react-router-dom. Right now, you’re using <Route> directly without that required wrapper, which is why React Router is throwing this error.
Here’s how to adjust your code step by step:
- Import
BrowserRouter(orHashRouterif you’re working on a static site or have server config limits) fromreact-router-dom. - Wrap your entire routing setup (including the
<Route>and any future<Link>components) inside this router component.
Here’s your updated code with these fixes applied:
import React from 'react' import { Route, BrowserRouter as Router, Link } from 'react-router-dom' // Added Router import import * as BooksAPI from './BooksAPI' import BookList from './BookList' import './App.css' class BooksApp extends React.Component { state = { books: [] } componentDidMount() { this.getBooks() } getBooks = () => { BooksAPI.getAll().then(data => { this.setState({ books: data }) }) } render() { return ( <div className="App"> {/* Wrap routes inside the Router context */} <Router> <Route exact path="/" render={() => ( <BookList books={this.state.books} /> )}/> </Router> </div> ) } } export default BooksApp
A quick side note: I aliased BrowserRouter to Router for brevity, but you can keep it as BrowserRouter if you prefer—either way works perfectly.
This should resolve the error right away, since your <Route> is now properly nested within a router context that React Router can recognize and work with.
内容的提问来源于stack exchange,提问作者Chris Camp

