反应路由器未在路由更改时呈现组件

时间:2020-07-09 12:00:19

标签: reactjs react-router

在应用程序的初始加载时,它将呈现与URL对应的正确组件。但是,当我更改单击链接时,它将不呈现任何内容。

index.tsx:

import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { store } from './store/store';
import { App } from './components/app/App';
import { BrowserRouter } from 'react-router-dom';



render(

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

我在其中放置路由器的Mye文件app.tsx: 这就是我想要的路由组件的样子。

import React from 'react';
import { Router, Route, Switch, Redirect, Link } from 'react-router-dom';
import { connect } from 'react-redux';
import {withRouter} from 'react-router-dom';
import { history } from '../../utils/helpers';
import { alertActions } from '../../store/actions'
import { PrivateRoute } from '../../routes';
import { Home, Login } from './components/';

interface AProps {
    alert: {
        message: string,
        type: string
    },
    clearAlerts: () => { type: string }
}

class App extends React.Component<AProps> {
    constructor(props: AProps) {
        super(props);

        history.listen((data) => {
            console.log(data);
            // clear alert on location change
            this.props.clearAlerts();
        });
    }

    render() {
        const { alert } = this.props;
        return (
            <Router history={history}>
                <div className="jumbotron">
                    <div className="container">
                        <div className="col-sm-8 col-sm-offset-2">
                            {alert.message &&
                                <div className={`alert ${alert.type}`}>{alert.message}</div>
                            }
                            <Link to="/login">Login</Link>
                            <Switch>
                                <Route path="/login" component={Login} />
                                {/* <PrivateRoute path="/" component={Home} /> */}
                                {/* <Redirect from="*" to="/" /> */}
                            </Switch>
                        </div>
                    </div>
                </div>
            </Router>
        );
    }
}

function mapState(state: any) {
    const { alert } = state;
    return { alert };
}

const actionCreators = {
    clearAlerts: alertActions.clear
};

const connectedApp = withRouter(connect(mapState, actionCreators)(App));
export { connectedApp as App };

我缺少某些东西来获取要单击“链接”进行渲染的组件吗?我没有收到任何控制台错误或任何告诉我有问题的信息。因此不确定组件是否包装不正确或是什么原因引起的。

2 个答案:

答案 0 :(得分:0)

更改此内容:

<Route path="/login" component={Login} />

对此:

<Route exact path="/login" component={Login} />

答案 1 :(得分:0)

您同时使用2个路由器。一个内部index文件,另一个内部app文件。您可能要删除其中之一。

例如,仅在index中留一个:

<Router history={history}>
    <App />
</Router>