反应您不应在<Router>外使用<withRouter(App)/>

时间:2020-01-23 08:22:27

标签: reactjs react-router react-router-v4 react-router-dom

我正在尝试在React中实现withRouter,所以我已将其导入为这样

import { BrowserRouter, Route, Switch , withRouter} from "react-router-dom";

然后在最后一行中,我写了以下内容

export default withRouter(App);

但是我收到错误

You should not use <withRouter(App) /> outside a <Router>

我正在尝试在我的app.js中实现它,如下所示

   class App extends React.Component {

    constructor(props) {
        super(props);

        console.log("PROPS APPJS")
        console.log(props)

        //checks if user is autheticated within the system in order to manage routes
        this.state = {
            authenticationChecked: false,
            isAuthenticated: false 
        }  

    }

    componentDidMount() {
        //calls the auth service to decide the auth state value
        isAuthenticated().then((result) => {
            if (result === true) {
                this.setState({ isAuthenticated: true, authenticationChecked: true})
            } else {
                this.setState({ isAuthenticated: false, authenticationChecked: true})
            }
        });
    }

    login = (email, password) => {
        var thiscomponent  = this;

        axios({
            method: 'post',
            url: 'http://localhost:3003/login',
            data: qs.stringify({ email, password }),
            headers: {
                'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
            }
        }).then(res => {
            console.log("set cookie")
            //the accestoken is set as a cookie in order to check routes
            Cookies.set('accesstoken', res.data.accesstoken);
            console.log("those are the props")
            console.log(this.props);
            this.setState({ isAuthenticated: true }, () => {
               thiscomponent.props.history.push('/'); 
            })

        }).catch(err => {
            console.log(err)
        })  
    }


    render() {
        if (!this.state.authenticationChecked) return null;

        return (

                <BrowserRouter>
                    <Switch>

                        <Route exact path="/login" render={(props) => <LoginPage login={this.login} {...props} />} />
                        <PrivateRoute authed={this.state.isAuthenticated} exact path="/register" render={(props) => <RegisterPage />} />
                        <PrivateRoute authed={this.state.isAuthenticated} exact path="/" render={(props) => <NewLandingPage  {...props}  />} />
                        <PrivateRoute authed={this.state.isAuthenticated} path="/page1" render={(props) => <Page1 />} />
                        <PrivateRoute authed={this.state.isAuthenticated} path="/page2" render={(props) => <Page2 />} />

                    </Switch>
                </BrowserRouter>
        )
    }
}
export default withRouter(App);

那里可能是什么问题?我实际上在那里有一个browserrouter,难道它也不应该也是路由器吗?

2 个答案:

答案 0 :(得分:3)

您在BrowserRouter中有App,但是当您使用withRouter时,用withRouter渲染孩子的父母必须有BrowserRouter。 >

因此从BrowserRouter中删除App并在App内渲染BrowserRouter

ReactDOM.render(
  <BrowserRouter>
    <App />
  </BrowserRouter, 
  container
)

此外,如果将方法用作箭头函数,则无需存储this上下文,因为它始终会指向类实例

答案 1 :(得分:0)

问题很可能来自您正在执行的身份验证检查。无论结果如何,您都将组件包装在withRouter()中,因此,如果authenticationChecked为false withRouter()无法访问任何路由,因此会出错。

您的解决方案可能是为登录名创建一个组件,然后将您的BrowserRouter等包装在这样的层次结构中:

return (
  <LoginProvider>
    <MyBrowserRouter>
      <Router>
    </MyBrowserRouter>
  </LoginProvider>
);

然后,您可以将MyBrowserRouter包裹在withRouter()中,但是根据您的身份验证检查,使LoginProvider的呈现带有孩子。