React路由器重定向页面但组件没有被渲染

IT技术 reactjs react-router react-router-dom
2021-05-23 06:11:54

我在 Route 更改时渲染组件有一个奇怪的问题。我使用的版本

{
  "react": "16.9.0",
  "react-dom": "16.9.0",
  "react-router-dom": "5.1.0"
}

这是我的路由配置

const Routes = () => {
    const isLoggedIn = StorageManager.get('session');
    return (
        <>
            <div className="background"></div>
            <MainLayout>
                <Header />
                <LeftSidebarMenu />
                <main className="main-container">
                    <Router history={history}>
                        <Switch>
                            <Redirect exact from="/" to="/categories" />
                            <Route exact path='/categories' component={Home} />
                            <Route exact path='/categories/new' component={CreateCategory} />
                            <Route exact path='/login' component={Login}
                                />
                        </Switch>
                    </Router>
                </main>
            </MainLayout>
        </>
    );
};

export default Routes;

主要问题是,当用户单击登录/注销时,如果成功/失败,它应该将用户重定向到适当的页面。实际上路由发生了变化,但组件没有被渲染。我使用history.push(PATH)来重定向用户。我不是react的初学者,老实说,我第一次遇到这种奇怪的问题。也许我混淆了我的路由器配置。

import React, {useState} from 'react';
import {withRouter, Link} from 'react-router-dom';
import Modal from 'react-modal';
import {shallowEqual, useSelector} from 'react-redux';
import Button from '../../components/core/button';
import StorageManager from '../../helpers/utilities/storageManager';
import FormGroup from '../../components/core/form/form-group';
import useForm from '../../helpers/custom-hooks';
import {signInRequest} from '../../redux/actions';

Modal.setAppElement('#root');

const Header = (props) => {
    const actionResult = useSelector((state) => state.admin.actionResult, shallowEqual);

    const {handleInputChange, handleSubmit} = useForm(signInRequest);
    const [session, setSession] = useState(StorageManager.get('session'));
    const [isLoginModalOpen, toggleLoginModal] = useState(false);
    const toggleModal = () => toggleLoginModal(!isLoginModalOpen);

    const handleLogin = () => {
        handleSubmit();
    };

    if(actionResult && actionResult.type === 'success' && isLoginModalOpen){
        setSession(StorageManager.get('session'));
        toggleLoginModal(false);
        props.history.push('/categories');
    }

    const handleLogout = () => {
        props.history.push('/login');
        StorageManager.remove('session');
        // setSession('');
    };

    return (
        <header className="header-section clearfix">
            <div className="header-container">
                <div className="header-left-menu">
                    <div className='header-logo-box'>
                        <a className="navbar-brand" href="#"><img src={require('../../images/logo.png')} alt=""/></a>
                    </div>
                </div>
                <Link to='/categories'>Link</Link>
                <div className="header-right-menu">
                    <div className="user-settings">
                        <img src={require('../../images/user.png')} alt=""/>
                        <span>Username</span>
                        {
                            session ?
                            <Button
                            className='btn-medium'
                            text='Выход'
                            onClick={handleLogout}
                        /> :
                        <Button
                            className='btn-medium'
                            text='Логин'
                            onClick={toggleModal}
                        />
                        }
                    </div>
                </div>
            </div>
            <Modal
                isOpen={isLoginModalOpen}
                style={customStyles}
                shouldCloseOnOverlayClick={true}
                onRequestClose={toggleModal}
                contentLabel="Login Modal"
            >
                <FormGroup className='form-group__modal'>
                    <h3>Login</h3>
                    <input
                        type="text"
                        placeholder="login"
                        name="login"
                        className='form-input'
                        onChange={handleInputChange}
                    />
                    <h3>Password</h3>
                    <input
                        type="text"
                        placeholder="password"
                        name="password"
                        className='form-input'
                        onChange={handleInputChange}
                    />
                    <Button
                        text='Sign in'
                        onClick={handleLogin}
                    />
                    <div className='invalid'>{actionResult ? actionResult.message : ''}</div>
                </FormGroup>
            </Modal>
        </header>
    );
};

export default withRouter(Header);
1个回答

您代码中的问题是您希望采取行动的地方没有被路由器提供者包装。即使您使用 withRouter 这是一个 HOC,它试图从最近的路由提供商那里获取路由器props,它也不会从用于包装所有路由的路由器中获取历史props。

您需要更新如何使用 Router 包装组件,例如

const Routes = () => {
    const isLoggedIn = StorageManager.get('session');
    return (
        <>
           <div className="background"></div>
           <Router history={history}>
            <MainLayout>
                <Header />
                <LeftSidebarMenu />
                <main className="main-container">
                        <Switch>
                            <Redirect exact from="/" to="/categories" />
                            <Route exact path='/categories' component={Home} />
                            <Route exact path='/categories/new' component={CreateCategory} />
                            <Route exact path='/login' component={Login}
                                />
                        </Switch>
                </main>
            </MainLayout>
          </Router>
        </>
    );
};

export default Routes;