React. New Router after login

2019-07-31 10:48发布

I have problem with Router in React, after login i change type state in Redux from 0 to 1, then i make switch in my App file, but i got error

Warning: [react-router] You cannot change <Router routes>; it will be ignored

This is my index.js, I want change all Route links if user is login (form with login work good and they change redux state type to 1):

@connect((store)=>{
    console.log(store)
    return {
        typeUser: store.app.type
    }

})
class App extends React.Component{

    render(){
        switch(this.props.typeUser){
            case 0:{
        return(
        <Router history={browserHistory}>
            <Route path={"/"} component={MainPage}></Route>
            <Route path={"/login"} component={Login}></Route>
            <Route path={"product/:nameProduct/:id"} component={ProductDetails}></Route>
        </Router>
        )
        break;
        }
            case 1:{
                return(
                <Router history={browserHistory}>
                    <Route path={"/"} component={MainPageAfterLogin}></Route>
                    <Route path={"/login"} component={LoginAfterLogin}></Route>
                </Router>
                )
                break;
            }
    }
    }
}

const app = document.getElementById('app');
ReactDOM.render(<Provider store={store}>
  <App/>
  </Provider>,app);

1条回答
放荡不羁爱自由
2楼-- · 2019-07-31 11:12

You cannot change the Router but you can change the Routes configuration that you have , so you can setup the Routes like

class App extends React.Component{
    render(){
        
        return(
        <Router history={browserHistory}>
             {this.props.typeUser === 0? <User1/>: <User2/>}
         
        </Router>
        )
       
    }
}

class User1 extends React.Component {
    render() {
    return (
        <div>
               <Route path={"/"} component={MainPage}></Route>
                <Route path={"/login"} component={Login}></Route>
                <Route path={"product/:nameProduct/:id"} component={ProductDetails}></Route> 
        </div>
    )
    } 
}

class User2 extends React.Component {
    render() {
    return (
        <div>
               <Route path={"/"} component={MainPage}></Route>
                <Route path={"/login"} component={Login}></Route>
             
        </div>
    ) 
    }
}

查看更多
登录 后发表回答