You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Router报错:不应在Router外部使用Route组件

Fixing the "You should not use or withRouter() outside a " Error

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:

  1. Import BrowserRouter (or HashRouter if you’re working on a static site or have server config limits) from react-router-dom.
  2. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:59:38