reactjs - 在登录页面上反应路由
问题描述
我正在尝试学习反应路由,这就是制作小型应用程序的原因。
我有 5 页
- 登录
- 注册
- 面板(登陆页面)
- 用户
- 错误
在 app.js 中
function App() {
const [user, setUser] = useState(null);
let history = useHistory();
return (
<Router>
<UserContext.Provider value={{ user, setUser }}>
<Switch>
<Route exact path={paths.login}>
<LoginWrapper history={history} />
</Route>
<Route exact path={paths.signup}>
<SignupWrapper history={history} />
</Route>
<PrivateRouting path={paths.dashboard}
isAuthenticated={user}
history={history}
component={Panel} />
<Route component={ErrorPage} />
</Switch>
</UserContext.Provider>
</Router>
);
}
成功登录后重定向面板(登陆页面)
Panel.js
import React, { useContext } from 'react';
import PropTypes from 'prop-types';
import {
BrowserRouter as Router, Route, Switch,
} from 'react-router-dom';
import Header from '../../Components/Header/Header';
import { UserContext } from '../../Utils/UserContext';
import {paths} from '../../Constants/Paths';
import User from '../User/User';
const Panel =(props)=>{
const {history}=props;
const { user } = useContext(UserContext);
console.log(props);
return (
<div>
<Header />
Home Page
<Router>
<Switch>
<Route exact path={paths.user}>
<User user={user} history={history} />
</Route>
</Switch>
</Router>
</div>
);
};
export default Panel;
Panel.propTypes = {
isAuthenticated: PropTypes.oneOfType([
PropTypes.object,
PropTypes.bool]),
history:PropTypes.object.isRequired,
};
import React from 'react';
import {
Route,
Redirect
} from 'react-router-dom';
import PropTypes from 'prop-types';
const PrivateRouting = ({ component: Component, isAuthenticated, ...rest }) => (
<Route {...rest} render={(props) => (
isAuthenticated
? <Component {...props} />
: <Redirect to="/" />
)} />
);
export default PrivateRouting;
PrivateRouting.propTypes = {
isAuthenticated: PropTypes.oneOfType([
PropTypes.object,
PropTypes.bool]),
component: PropTypes.elementType.isRequired,
};
PrivateRouting.defaultProps = {
name: false
};
当我尝试重定向 /user(paths.user) 时,它会自动重定向到错误页面
如何在面板中创建路由
解决方案
推荐阅读
- asp.net - OData WebAPI:如何在Function中硬编码OrderBy?
- c++ - 多线程数据到数组 C++
- javascript - 定位动态添加的视频
- r - 传单“无法推断 lng 列”,但 df 显示加载的 lat 和 lng 列
- java - 如何在不拆分字符串的情况下检查字符串是否具有某种模式?
- javascript - 如何管理流以处理 node.js 中的传入数据
- laravel - Carbon::parse 获取日期
- javascript - 如何从按钮增加java脚本函数中的全局变量?
- ssh - 如何在 Github Actions 中使用 ssh 身份文件
- javascript - 未选中的 Vuetify v-checkbox 图标没有为 Font Awesome 4 应用正确的类