简体   繁体   中英

Page doesn't load when typing url of a private component into browser's adress bar (React-router v4)

I'm making an app with authentication, using react-router and react-router-redux for handling routing. My routes get rendered as expected when I start from a non-private route, hovewer when I type a private route's url directly into the browser's adress bar nothing gets loaded(screenshot). How can I fix this problem?

PrivateRoute.js

const PrivateRoute = ({userStatus, component: Component, ...rest }) => {

    const stuffToShow = (props) => {
        if(userStatus.authenticated) {
            return <Component {...props}/>;
        }
        return <Redirect to={{
            pathname: '/login',
            state: { from: props.location }
        }}/>
    };

    return <Route exact {...rest} render={stuffToShow}/>

};

export default connectComponent(['userStatus'], PrivateRoute);

routes.js

export function renderRoutes(routes) {
    return routes.map((route, i) => {
        if(route.private) {
            return <PrivateRoute key={i} {...route} />;
        }
        return <Route key={i} {...route}/>;
    })
}

const routes = [
    {
        path: '/',
        exact:true,
        component: Home
    },
    {
        path: '/login',
        exact:true,
        component: Login
    },
    {
        path: '/registration',
        exact:true,
        component: Registration
    },
    {
        path: '/users/:id',
        exact:true,
        component: UserPage,
        private: true
    }, 
    {
        path: '/users',
        exact:true,
        component: Users,
        private: true
    },
    {
        path: '/goodBye',
        exact:true,
        component: Goodbye
    },
    {
        path: '*',
        component: NoMatch
    }
];

root:

    <Provider store={store}>
        <Router history={history}>
            <div>
               <Header />
                <Switch>
                    {renderRoutes(routes)}
                </Switch> 
            </div>
        </Router>
    </Provider>

How I render html on express server:

        this.app.use('/api/users', userRoute);
        this.app.use('/api/blogPosts', blogPostsRoute);
        this.app.use('*',(req,res) => res.sendFile(path.resolve(__dirname, '..', 'public', 'index.html')));

在此处输入图片说明

Try to modify this part:

const stuffToShow = (props) => {
    if(userStatus.authenticated) {
        return <Component {...props}/>;
    }
    return (
      <Redirect to={{
        pathname: '/login',
        state: { from: props.location }
      }}/>
    );
};

The <Redirect /> is multiple lines, should be enclosed with () . That's my best guess of your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM