【问题标题】:How to solve "Uncaught TypeError: Cannot read property 'params' of undefined" reactjs + django如何解决“未捕获的类型错误:无法读取未定义的属性'参数'”reactjs + django
【发布时间】:2021-05-10 02:22:50
【问题描述】:

我正在练习 reactjs 看这个视频https://www.youtube.com/watch?v=5rh853GTgKo&list=PLJRGQoqpRwdfoa9591BcUS6NmMpZcvFsM&index=9

我想用uid和token验证我的信息,但是不知道怎么投递。

在这段代码中:Activate.js in container

import React, { useState } from 'react';
import { Redirect } from 'react-router-dom';
import { connect } from 'react-redux';
import { verify } from '../actions/auth';

const Activate = ({ verify, match }) => {
const [verified, setVerified] = useState(false);

const verify_account = e => {
  const uid = match.params.uid; // I Think This part is Problem
  const token = match.params.token;

  verify(uid, token);
  setVerified(true);
};


if (verified) {
   return <Redirect to='/' />
}

这段代码:auth.js in actions

export const verify = (uid, token) => async dispatch => {
  const config = {
    headers: {
      'Content-Type': 'application/json'
    }
  };

  const body = JSON.stringify({ uid, token });

  try {
    await axios.post(`${process.env.REACT_APP_API_URL}/auth/users/activation/`, body, config);

    dispatch ({
      type: ACTIVATION_SUCCESS,
    });
  } catch (err) {
    dispatch ({
      type: ACTIVATION_FAIL
    });
  }
}

我想我没有渲染 uid,token 但我很困惑如何做到这一点

App.js 代码:

<Router>
  <Layout>
    <Switch>
      <Route exact path ='/activate/:uid/:token'>
        <Activate />
      </Route>
    </Switch>
  </Layout>
</Router>

如果有任何帮助,我将不胜感激。 :)

【问题讨论】:

  • 你能发布你的实际错误吗?顺便说一句,match 似乎在某种程度上是未定义的
  • @DDomen 什么是实际错误?在我的 chrome 控制台中“const uid = match.params.uid;”有一个问题““未捕获的类型错误:无法读取未定义的属性'params'””
  • 堆栈跟踪?你在哪一行得到错误?另外,您在哪里调用 Activate 函数?因为貌似match参数是undefined
  • match 应该由父 Route 组件注入到 props 中。您的应用程序中是否还有其他地方使用了Activate 组件,它不是Route 的子组件?
  • 您对verify 有疑问。您写道,您的 Activate 组件采用了一个 prop verify,因此在该函数的范围内,变量 verify 将引用 prop verify 而不是您导入的函数 verify。如果要引用函数,请使用相同的变量丢弃 prop。

标签: javascript reactjs react-router jwt


【解决方案1】:

使用useParams钩子提取uidtoken参数:

import React, { useState } from 'react';
import { Redirect, useParams } from 'react-router-dom';
import { connect } from 'react-redux';
import { verify } from '../actions/auth';

const Activate = ({ verify }) => {
const [verified, setVerified] = useState(false);
const { uid, token } = useParams();

const verify_account = e => {
  verify(uid, token);
  setVerified(true);
};


if (verified) {
   return <Redirect to='/' />
}

【讨论】:

  • useParams 有助于清晰,但他们将其用作Route 的渲染函数,因此他们应该在道具中获得match。不过,他们的代码还有很多其他问题。很难准确说出导致此特定错误的故障所在。
猜你喜欢
  • 2016-08-09
  • 1970-01-01
  • 1970-01-01
  • 2018-04-14
  • 2019-10-15
  • 2017-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多