首次登录后 React 不重定向。但在强制重定向并再次执行登录操作后重定向

2024-03-02

我有一个登录表单,单击后会调用以下函数。

总结一下,从 api 获取响应,如果有效,则设置 cookie,然后使用this.props.history.push()

handleSubmit(event) {
    event.preventDefault();
    const { email, password } = this.state;
    axios({
        method: 'post',
        url: 'http://localhost:3003/login',
        data: qs.stringify({ email, password }),
        headers: {
            'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
        }
    }).then(res => {
        console.log("set cookie")
        //the accestoken is set as a cookie in order to check routes
        Cookies.set('accesstoken', res.data.accesstoken);
        console.log("those are the props")
        console.log(this.props);

        this.props.history.push('/'); //the bug


    }).catch(err => {
        console.log(err)
    })  


}

但我面临的问题是,当我第一次登录时,重定向将不起作用。它设置了所有 cookie 等,但它实际上从未将用户重定向到所需的目录。因此,我被迫通过在浏览器搜索栏中输入我想要的路线来重定向自己。

这意味着一旦我强迫自己进入所需的目录,如果我注销(基本上删除cookie),然后尝试再次登录。这次重定向起作用了。

它会一直工作,直到我使用 ctrl+F5 清除所有缓存,这恰好导致我在第一次登录时遇到的相同问题,所以我不得不再次手动重定向自己。

编辑:这就是我的路线的样子

<BrowserRouter>
                <Switch>

                    <Route exact path="/login" render={(props) => <LoginPage {...props}/>} />

                    <PrivateRoute authed={this.state.isAuthenticated} exact path="/" render={(props) => <RegisterPage />} />

                </Switch>
            </BrowserRouter>

这些是我的私人路线

import { Route } from 'react-router-dom';

从“反应”导入反应; 从“react-router”导入{重定向};

export default ({ component: Component, render: renderFn, authed,  ...rest }) =>{
  //The privateroute is fed with the auth state of app.js and evaluates the render based on that . If flase always renders "/"
  if (Component){
    return (
      <Route
      {...rest}
      render={props =>
        authed === true ? (
          <Component {...props} />
        ) : (
            <Redirect to={{ pathname: '/login', state: { from: props.location } }} />
          )
      }
    />
    )
  } else {
    return ( //Second case is for iframe based renders
      <Route {...rest} render={props => authed === true ? renderFn(props) : <Redirect to={{ pathname: '/login', state: { from: props.location } }} /> } /> 
      );
  }
}

EDIT2:

app.js

    constructor(props) {
        super(props);

        console.log("PROPS APPJS")
        console.log(props)

        //checks if user is autheticated within the system in order to manage routes
        this.state = {
            authenticationChecked: false,
            isAuthenticated: false 

        }  



    }


    componentDidMount() {
        //calls the auth service to decide the auth state value
        isAuthenticated().then((result) => {
            if (result === true) {
                this.setState({ isAuthenticated: true, authenticationChecked: true})
            } else {
                this.setState({ isAuthenticated: false, authenticationChecked: true})
            }
        });
    }

    login = (email, password) => {
        var thiscomponent  = this;
        axios({
            method: 'post',
            url: 'http://localhost:3003/login',
            data: qs.stringify({ email, password }),
            headers: {
                'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
            }
        }).then(res => {
            console.log("set cookie")
            //the accestoken is set as a cookie in order to check routes
            Cookies.set('accesstoken', res.data.accesstoken);
            console.log("those are the props")
            console.log(this.props);
            this.setState({ isAuthenticated: true }, () => {
               thiscomponent.props.history.push('/'); //the bug
            })

        }).catch(err => {
            console.log(err)
        })  
    }

.
.
.
.
.
.
.
<BrowserRouter>
                <Switch>

                    <PrivateRoute authed={this.state.isAuthenticated} exact path="/" render={(props) => <NewLandingPage login={this.login} {...props} exact />} />
                </Switch>
            </BrowserRouter>

登录页面

 handleSubmit(event) {
        const { email, password } = this.state;
        this.props.login(email, password)
        event.preventDefault();


    }

编辑:登录页面道具

  {"history":{"length":15,"action":"POP","location":{"pathname":"/login","search":"?email=test4%40test.com&password=test","hash":""}},"location":{"pathname":"/login","search":"?email=test4%40test.com&password=test","hash":""},"match":{"path":"/login","url":"/login","isExact":true,"params":{}}}

您在何时何地设置 isAuthenticated? – lehm.ro 7 分钟前
@lehm.ro 在我的 app.js 中的 componentDidMount() 期间,默认 isAuthenticated 为 false – mouchin777 6 分钟前 然后,一旦您重定向,您必须使用 this.setState 使其变为 true,否则您的私有路由将不会显示。但为此,您需要将 true 状态传递给 app.js,然后触发一个函数来 setState 为 isAuthenticated true,然后重定向到该路由

设置您的历史记录以在 app.js 中工作,而无需通过 props 传递:未捕获的类型错误:无法读取未定义的属性“push”(React-Router-Dom) https://stackoverflow.com/questions/44009618/uncaught-typeerror-cannot-read-property-push-of-undefined-react-router-dom

为了利用history in the App组件将其与withRouter。你需要利用withRouter只有当你的 组件没有接收到Router props,

当您的组件是a 的嵌套子级 由 Router 渲染的组件 or 你还没有通过路由器 它的道具 or 当组件没有链接到 Router 时在 all 并呈现为独立于路由的组件。

import React from 'react';
import { Route , withRouter} from 'react-router-dom';
import Dashboard from './Dashboard';
import Bldgs from './Bldgs';

var selectedTab;

class App extends React.Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
    selectedTab = 0;
  }

  handleClick(value) {
    selectedTab = value;
    // console.log(selectedTab);
    this.props.history.push('/Bldgs');
    // console.log(this.props);
  }

  render() {
    var _this = this;

    return (
      <div>
        <Route exact path="/" render={(props) => <Dashboard {...props} handleClick={_this.handleClick} />} />
        <Route path="/Bldgs" component={Bldgs} curTab={selectedTab} />
      </div>
    );
  }
}

export default withRouter(App);

[文档][1]在路由器上

[1]: https://reacttraining.com/react-router/web/api/withRouter https://reacttraining.com/react-router/web/api/withRouter

App.js 中的更改

<Route exact path="/login" render={(props) => <LoginPage login={this.login} {...props}   />} />

and add

login = (email, password) => {
    var thiscomponent = this;
    axios({
        method: 'post',
        url: 'http://localhost:3003/login',
        data: qs.stringify({ email, password }),
        headers: {
            'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
        }
    }).then(res => {
        console.log("set cookie")
        //the accestoken is set as a cookie in order to check routes
        Cookies.set('accesstoken', res.data.accesstoken);
        console.log("those are the props")
        console.log(this.props);
        this.setState({ isAuthenticated: true }, () => {
           thiscomponent.props.history.push('/'); //the bug
        })

    }).catch(err => {
        console.log(err)
    })  
}

并在登录页面中

handleSubmit(event) {
    const { email, password } = this.state;
    this.props.login(email, password)
    event.preventDefault();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

首次登录后 React 不重定向。但在强制重定向并再次执行登录操作后重定向 的相关文章

  • 如何在 Gatsby 页面上包含本地 JavaScript?

    我是一个完全的 React 新手 我想这里有些基本的东西我不太明白 默认的 Gatsby 页面如下所示 有没有办法像这样使用本地 js 文件 我想要实现的是让反应忽略script js但仍然让客户端使用它 默认的 Gatsby 页面看起来像
  • 如何使用 Coffeescript 在 React 中渲染 HTML 标签?

    我目前正在学习 ReactJS 以及如何使用 Ruby on Rails 作为其后端 所以如果我做出愚蠢的假设 我深表歉意 请随意责骂我 我正在关注一个教程 其中作者使用 Coffeescript 而不是 ES6 来处理他的 ReactJS
  • 即使未显式使用“componentWillMount”,“componentWillMount”警告仍可见

    在我的代码中 我没有任何明确的用途componentWillMount 但我在运行时仍然看到一些警告webpack react dom development js 12386 警告 componentWillMount 已重命名 不建议使
  • Firestore 查询 .toUpperCase() 不起作用

    我正在尝试创建一个网站 使用户能够搜索 Firebase Firestore 中的文档集合 该过程涉及将用户的输入保存为状态 useState 并利用 useEffect 挂钩来查询 Firebase 数据库 但是 我遇到了一个问题 即使用
  • 这种类型注释在没有 TypeScript 的 React 代码中如何工作?

    我在看这段代码示例 https reacttraining com react router web example auth workflow在 ReactRouter 页面上 这篇文章很有趣 const PrivateRoute com
  • React JS 服务器端问题 - 找不到窗口

    你好 我正在尝试在我的reactJS项目中使用react rte 我有服务器端渲染 每次我想使用这个包时 我都会得到 return msie 6 9 b test window navigator userAgent toLowerCase
  • 使用 ref 触发反应 dropzone 不起作用

    我正在实现这个库 https github com felixrieseberg React Dropzone Component https github com felixrieseberg React Dropzone Compone
  • 没有 Props 的 TypeScript React State

    我想利用 TypeScript 中的静态和强类型 但仅限于状态 因为我不打算采用任何道具 当我尝试传递接口时 最终出现错误 import as React from react import Link from react router d
  • 在 javascript 文件中设置 firebase-admin sdk

    我的最终目标是使用用户 ID 获取用户电子邮件 到目前为止 我发现我需要使用 firebase admin SDK 现在我有这个代码 var admin require firebase admin var serviceAccount r
  • 有没有办法在 React.render() 函数中渲染多个 React 组件?

    例如我可以这样做 import React from react import PanelA from panelA jsx import PanelB from panelB jsx React render
  • React 在同一组件中渲染多个模态

    我对 React 和一般编码都很陌生 我试图在同一组件中渲染多个模态 但它们都是同时渲染的 因此看起来所有链接都在最后一个模态中渲染文本 这是状态设置的地方 class Header extends React Component cons
  • 在react-admin中通过REST API进行基于cookie的身份验证

    我是反应管理新手 我已经阅读了 stackoverflow 中的所有问题 也用谷歌搜索了我的问题 但没有找到任何有用的解决方案 我正在设置 React admin 来替换我的一个项目的现有管理页面 我通过 REST API 使用基于 coo
  • ReactCSSTransitionGroup 组件WillLeave 未调用

    我尝试使用 ReactCssTransition 但不知何故该事件没有被调用 componentWillLeave 这是我的组件 import React Component from react import TransitionGrou
  • p5 向量减法“sub”返回错误

    我一直在尝试将 p5 草图上传到 React 构建中 使用react p5 wrapper 我能够成功在屏幕上渲染画布 但是 某些矢量函数会导致错误 var distance this position dist ball position
  • 可下载文件 - 盖茨比

    由于某种原因 尝试下载文件时失败 我尝试了几种不同的方法 但都失败了 我读过一些关于 pdf word 文件在盖茨比中被 禁止 的内容 默认 a href route to file a 好像不行 显示下载失败 任何帮助表示赞赏 See 将
  • 您在 javascript Web 应用程序中使用的第三方 API ApiKey 存储在哪里?

    如何以及在何处存储您在 javascript Web 应用程序中使用的第三方 API ApiKey 又名 AppId AppSecret AppKey 如果它用于获取 URL 并且在浏览器网络选项卡中可见 我是否应该对其保密 示例 在我的
  • 打字稿 - 字符串'不可分配给类型'FC

    我收到以下错误 Type props PropsWithChildren lt amount number gt gt string is not assignable to type FC lt amount number gt Type
  • React Context 的范围是什么?

    我不清楚在哪里Context可以在 React 应用程序中创建 我可以在组件树中的任何位置创建上下文吗 如果可以 该上下文的范围是否仅限于创建它的子级 或者 Context 本质上是全局的 我可以在文档中的哪里找到这个 案例 我在页面上多次
  • 仅显示某些路由的组件 - React

    我正在 React 中开发一个带有登录界面的网站 该网站显示一个自定义导航组件 但是我不希望它显示在主路线 即登录页面 上 但据我了解 静态组件不会在路线更改时重新呈现 这准确吗 我正在使用 React Router 来处理所有路由 这是我
  • React无限滚动scrollableTarget动态获取id?

    我在我的项目中使用react infinite scroll component 如何让scrollableTarget动态获取item id 我试过这样scrollableTarget item id 但它不起作用 必须与该 div 具有

随机推荐

  • 带有networkx的超图

    有人熟悉networkx吗 我尝试获取一个超图 我想将超边设置为列表中的其他彩色节点 大小取决于它们的值 我想将节点设置为其他列表之外 networkx 网站上的文档和示例确实很少 但我确信这是可能的 我开始于这个例子 https netw
  • 如何从 SQL Server 的列中删除不间断空格?

    我正在尝试删除不间断空格 CHAR 160 来自我表中的一个字段 我尝试过使用类似的函数RTRIM 摆脱它 但价值仍然存在 我需要做什么才能从列中删除不间断空格 尝试使用REPLACE http msdn microsoft com en
  • Eonasdan/bootstrap-datetimepicker 日期时间选择器通过外部 javascript 调用重置

    我有用Eonasdan bootstrap datetimepicker 版本 4 17 47 现在解释一下当我从文本框打开 bootstrap datetimepicker 并选择日期时的情况 之后我有一个清除按钮 onclick 我清除
  • 在 Vega Lite 中使用数据作为数组而不是表

    如何在 VegaLite 中使用数组数据 我想将数据用作数组 dates 1 2 3 prices1 1 2 1 prices2 1 5 1 2 而不是 VegaLite 中传统使用的表数据 date 1 price 1 symbol 1
  • 查找包中的所有函数(包括私有函数)

    I know ls package grid and find funs package grid in mvbutils但显然他们都找不到只能在内部或通过以下方式访问的非导出函数和方法 or getAnywhere 我必须在以下位置获取文
  • 我可以在 VS 中构建这个项目,但不能使用 msbuild

    我正在尝试在 nuget 应用程序中构建一个 ms 测试项目 我的项目结构是这样的 MyPackage gt MyPackage gt MyPackageTest 如果我打开 VS 并右键单击并构建 MyPackageTest 它可以工作
  • 找不到与给定名称“@style/Theme.Holo.Light.DarkActionBar”匹配的资源

    平台 4 3 API级别 18 AndroidManifest xml
  • 单击 IE 中图像上方的 div

    我有一个图像 上面可能有一些 div 指定该图像中的某些选择 这些 div 应该是可点击的 像这样的东西 divOuter width 500px height 500px border 2px solid 0000FF position
  • Cheerio / jquery 选择器:如何获取标签 a 中的文本?

    我正在尝试访问网站上的链接 该网站看起来像第一个代码示例 链接位于不同的 div 容器中 div div class class1 div class item class1 a href http www example com 1 ex
  • Spring Boot 的外部库文件夹

    我想知道如何为我的 Spring Boot 应用程序外部化所有 jdbc 驱动程序 我不想在构建应用程序后将 jdbc 驱动程序插入到我的 fat jar 中 有没有办法设置 java vm 参数 通知 jar 执行应包含哪个外部文件夹 或
  • 在 MSBuild 参数中设置应用程序名称

    我正在使用这个从命令行部署我的网络应用程序 msbuild WebApplication1 csproj t Package p configuration release 它工作正常 但部署的应用程序与项目设置页面中使用的名称相同 我想使
  • 在 R 中创建滚动列表

    给定一个向量 数据框的列 我想创建一个滚动向量 l 0 10 将返回 窗口为 3 0 1 2 1 2 3 2 3 4 3 4 5 1 滚动应用 r是一个 9x3 矩阵 其每一行都是所要求的列表元素之一 并且split将其转换为向量列表 尽管
  • Godot:调用外部方法

    经过大量谷歌搜索 我仍然不明白什么可能是一个简单的解决方案 场景 主要 包含一个 TileMap Grid 并附有一个脚本 Grid gd 场景 玩家 包含一个 KinematicBody2D Player 及其附加脚本 Player gd
  • 将嵌入资源保存到文件系统

    我使用此代码加载嵌入资源 位图图像 HRSRC hResInfo FindResource hInstance MAKEINTRESOURCE resourceId RT BITMAP HGLOBAL hRes LoadResource h
  • 在php联系表单中捕获用户的IP地址

    我正在尝试从 php 联系表单获取用户 IP 地址 我有以下代码 但我想知道以这种方式使用 clean string 向自己发送 IP 地址是否有效
  • Django:禁止(未设置 CSRF cookie。)

    我遇到了 CSRF cookie 未设置 的问题 我所需要的只是外部计费平台将更新发送到 django 服务器 在本地它可以与 Postman 一起使用 但在演示服务器中它不起作用 Code views py from django vie
  • 更改应用程序和任务栏图标 - Python/Tkinter

    我一直在使用 Tkinter 编写一个非常简单的 Python 脚本 我正在使用Python 2 7 3 如何更改其应用程序图标 资源管理器窗口中显示的 文件 图标和开始 所有程序例如 窗口 不是 文件类型 图标 也不是应用程序图标的主窗口
  • VirtualTreeView 的 Firemonkey 版本

    有谁知道是否有流行的 Firemonkey 版本在准备 另外 是否有人收集了一些将自定义控件移植到 Firemonkey 的经验 并且可以估计将虚拟树视图移植到 Firemonkey 需要多少工作 我们需要这个控件 并且只有当我们能让这个控
  • log4j 打印错误的字符

    有人报告我给他的使用 log4j 的程序无法正确打印字符 他告诉我 在文件中打印为 例如 Vid o 变成 Vid o 这可能是一些编码问题 但我喜欢重现问题以证明它已修复 我无法找到有关该主题的良好 且简短 文档 因此 是什么导致了这个问
  • 首次登录后 React 不重定向。但在强制重定向并再次执行登录操作后重定向

    我有一个登录表单 单击后会调用以下函数 总结一下 从 api 获取响应 如果有效 则设置 cookie 然后使用this props history push handleSubmit event event preventDefault