reactjs - 反应重定向不呈现组件
问题描述
我目前正在学习 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 标签也是如此。我真的很感激任何帮助。谢谢!
解决方案
您的<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>
推荐阅读
- visual-studio-code - VSCODE 精确键绑定,想知道当前上下文。怎么做?
- html - css 动画没有响应 span:nth-child
- c# - 使用 Raspberry Pi Raspberrian 的带有控制台应用程序的 C# 相机流服务器
- php - LaravelLocalization 无法翻译 nwidart laravel 模块的路由
- javascript - 如何存储在浏览器中单击提交按钮的计数
- swift - Network.framework:nw_read_request_get_maximum_datagram_count
- java - USACO 2018 年 12 月铜奖的错误输出
- c - 当 i 已经用 0 和 if 条件以及为什么初始化时,它的值是多少?
- python - 如何从每个一级索引的最大二级索引的单元格中选择值?
- python - OpenCV 图像处理后 QLabel 不更新图像