错误:不变失败:您不应在 <Router> 之外使用 <withRouter(App) />

时间:2021-01-12 08:43:28

标签: javascript reactjs router react-router-dom

我很确定我在正确的地方使用,但我仍然遇到错误。知道为什么吗?

错误:不变式失败:您不应在

之外使用

为丑陋的代码道歉。我是新手。

 render()
       return (
        <BrowserRouter>
          <div className="App">
    
            <Route path="/" exact render={ 
              (props)=> {
              return(
                <div>
                  <input type='text' onChange={this.formChangeHandler}/>
                  <p><button onClick={ () => this.postData(this.state.message)}>Submit</button></p>   
                </div>
              )}
            }/> 
    
            <Route path="/post" exact render={
              (props)=> {
                  return(
                  <div>
                    <b>SUCCESS!</b>
                  </div>
                )
                }
              }/> 
            </div>
          </BrowserRouter>
      );
     }
    }
    export default withRouter(App);

2 个答案:

答案 0 :(得分:0)

withRouter

您可以通过 withRouter 高阶组件访问 history 对象的属性和最接近的 匹配。每当渲染时,withRouter 都会将更新的匹配、位置和历史道具传递给包装的组件。

import React from "react";
import PropTypes from "prop-types";
import { withRouter } from "react-router";

// A simple component that shows the pathname of the current location
class ShowTheLocation extends React.Component {
  static propTypes = {
    match: PropTypes.object.isRequired,
    location: PropTypes.object.isRequired,
    history: PropTypes.object.isRequired
  };

  render() {
    const { match, location, history } = this.props;

    return <div>You are now at {location.pathname}</div>;
  }
}

// Create a new component that is "connected" (to borrow redux
// terminology) to the router.
const ShowTheLocationWithRouter = withRouter(ShowTheLocation);

答案 1 :(得分:0)

正如您的错误所说,您无法将组件连接到路由器之外的路由器。并且您正在尝试将呈现路由器的组件连接到路由器

所以你需要做这样的事情

// Main.js
export default class Main extends PureComponent {
    render (
        <BrowserRouter>
            <App />
        </BrowserRouter>
    )
}
// App.js
class App extends PureComponent {
    render (
        <div className="app">
            ...
        </div>
    )
}

export default withRouter(App)