首页 > 解决方案 > 反应重定向不呈现组件

问题描述

我目前正在学习 React,现在我正在尝试在 React 中实现重定向。我有一个名为 logout.js 的文件,它将用户重定向到另一个文件 Mello.js。重定向成功,因为 URL 在浏览器中更改为/Mello,但未呈现相同的组件。我的 logout.js 文件是:

import React from 'react';
import axios from 'axios';
import {BrowserRouter as Router,Route,Switch,Redirect} from 'react-router-dom';
import Hello from './Hello';
import Mello from './Mello';
class logout extends React.Component{
constructor(props){
    super(props);
    this.state={
        isloggedout: false
    }
}
componentDidMount(){
    axios.get("http://127.0.0.1:3000/logout").
    then(res=>{this.setState({isloggedout:res.data.state})});
    console.log("hello from logout");
}
render(){
    return (
        this.state.isloggedout?<Router><Redirect to="/Mello" /></Router>:<p>Not allowed</p>
        );
}
}
export default logout;

Mello.js 是:

import React from 'react';
class Mello extends React.Component{
constructor(props){
    super(props);
}
render(){
    console.log("Hello from Mello");
    return(<div>
        <h1>Hello from Mello</h1>
        </div>
        );
}
};

export default Mello;

我设置所有路线的代码:

<Router>
            <Switch>
                <Route exact path="/" component={Hello} />
                <Route exact path="/Mello" component={Mello} />
                <Route exact path="/logout" component={logout} />
            </Switch>
</Router>

当重定向发生时,控制台上没有打印任何内容(甚至没有任何错误),h1 标签也是如此。我真的很感激任何帮助。谢谢!

标签: reactjs

解决方案


您的<Redirect><Route>位于不同的路由器中,因此它们没有连接起来。

它们都必须在同一个<Router>元素中。

{this.state.isloggedout? <Router><Redirect to="/Mello" /><Switch> <Route exact path="/Mello" component={Mello} /></Switch></Router>}

(可能不完全是最好的方法,但根本问题是你<Route><Redirect>必须属于同一<Router>

https://reacttraining.com/react-router/web/api/Redirect

<Router>
<Switch>
  <Redirect from='/old-path' to='/new-path' />
  <Route path='/new-path'>
    <Place />
  </Route>
</Switch>
</Router>

或者

<Router>
<Route exact path="/">
  {loggedIn ? <Redirect to="/dashboard" /> : <PublicHomePage />}
</Route>
</Router>

推荐阅读