本文介绍了REACT JS:TypeError:无法读取未定义的属性“参数"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的 React 前端似乎有问题我正在处理我的 Reset.js 页面,并且不断收到错误消息
TypeError: 无法读取未定义的属性 'params'
一旦我转到 Reset.js 页面 就会发生这种情况,这是如何工作的,当用户忘记他们的密码时,他们会按顺序收到一封电子邮件使用 jwt 重置他们的密码,当点击电子邮件中的链接时,它会将您路由到 Reset.js 页面,您将在此处填写凭据以重置密码.
但是在到达路由的过程中,我收到一个 TypeError: Cannot read property 'params' of undefined
错误,这是下面显示的受影响的 React js 代码行.
14 |const { password1, password2, textChange, token } = formData;15 |16 |useEffect(() => {>17 |let token = match.params.token//**此处导致错误无法读取未定义的属性'params'**|^ 18 |如果(令牌){19 |setFormData({...formData, token,})20 |}
这也是Chrome错误的截图,方便查看.
这是我在 React 中 Reset.js 页面的完整代码.
import React, { useState, useEffect } from 'react';从'../assets/reset.svg'导入authSvg;导入 { ToastContainer, toast } from 'react-toastify';从 'axios' 导入 axios;const Reset = ({match}) =>{const [formData, setFormData] = useState({密码 1: '',密码 2: '',令牌:'',textChange: '提交'});//eslint-disable-next-line no-unused-varsconst { password1, password2, textChange, token } = formData;useEffect(() => {let token = match.params.token//**这里导致错误无法读取未定义的属性'params'**如果(令牌){setFormData({...formData, token,})}//eslint-disable-next-line react-hooks/exhaustive-deps}, [])const handleChange = text =>e =>{setFormData({ ...formData, [text]: e.target.value });};const handleSubmit = e =>{控制台日志(密码1,密码2)e.preventDefault();if ((password1 === password2) && password1 && password2) {setFormData({ ...formData, textChange: '提交' });公理.put(`${process.env.REACT_APP_API_URL}/password/reset`, {新密码:密码1,重置密码链接:令牌}).then(res => {控制台.日志(res.data.message)设置表格数据({...表单数据,密码 1: '',密码2:''});toast.success(res.data.message);}).catch(错误 => {toast.error('有问题再试一次');});} 别的 {toast.error('密码不匹配');}};返回 (<div className='min-h-screen bg-gray-100 text-gray-900 flex justify-center'><吐司容器/><div className='max-w-screen-xl m-0 sm:m-20 bg-white shadow sm:rounded-lg flex justify-center flex-1'><div className='lg:w-1/2 xl:w-5/12 p-6 sm:p-12'><div className='mt-12 flex flex-col items-center'><h1 className='text-2xl xl:text-3xl font-extrabold'>重置你的密码<div className='w-full flex-1 mt-8 text-indigo-500'><表格className='mx-auto max-w-xs 相对'onSubmit={handleSubmit}></表单>
<div className='flex-1 bg-indigo-100 text-center hidden lg:flex'>
;
);};导出默认重置;
我也尝试通过添加 useParams
来修复它,尽管它似乎没有按计划进行锻炼,但这是我尝试进行但没有锻炼的修复,所以我决定联系一些帮助,
这是我在下面尝试过的;
import { useParams } from 'react-router-dom';从 'jsonwebtoken' 导入 jwt;//添加这个是因为我使用 jwt.decode 的方式textChange: '提交'});//eslint-disable-next-line no-unused-varsconst { password1, password2, textChange } = formData;//我从这里删除了令牌,因为我们在下面的参数中的第 21 行调用它//const { password1, password2, textChange, token } = formData;//这是原始代码格式,上面是我编辑的.const { token } = useParams();useEffect(() => {让密码 = jwt.decode(token);//在这里添加了 jwt.decode(token) 虽然一开始它是 match.params.token//让 token = match.params.token如果(令牌){setFormData({...formData,password, token,})//在这里添加了密码,但它不应该是他们对原始代码的引用.}//eslint-disable-next-line react-hooks/exhaustive-deps}, [])
当我使用 useParams 在 Chrome 控制台 中读取上述代码时显示的错误.
PUT http://localhost:4000/api/password/reset 400(错误请求)
下面是错误,但以截图形式方便查看,但与上面的相同.然后下面是我用于 Reset.js 页面
的路由
import { Navigate } from 'react-router-dom';从 'src/components/DashboardLayout' 导入 DashboardLayout;从 'src/components/MainLayout' 导入 MainLayout;从 'src/pages/Account' 导入帐户;从 'src/pages/CustomerList' 导入 CustomerList;从 'src/pages/AssistantList' 导入 AssistantList;从 'src/pages/MarketList' 导入 MarketList;从 'src/pages/Dashboard' 导入仪表板;从 'src/pages/Login' 导入登录;从 'src/pages/NotFound' 导入 NotFound;从 'src/pages/ProductList' 导入 ProductList;从 'src/pages/Register' 导入注册;从src/pages/Settings"导入设置;从src/pages/Activate"导入激活;从 'src/pages/Forget' 导入忘记;从 'src/pages/Reset' 导入重置;//这就是我导入Reset.js页面的方式const 路由 = [{路径:'应用',元素:<DashboardLayout/>,孩子们: [{ path: 'account', element: },{ 路径:'助手',元素:<AssistantList/>},{ 路径:'客户',元素:<CustomerList/>},{ 路径:'仪表板',元素:<仪表板/>},{ 路径:'市场',元素:<MarketList/>},{ 路径:'产品',元素:<ProductList/>},{ 路径:'设置',元素:<设置/>},{路径:'*',元素:<导航到=/404";/>}]},{小路: '/',元素:<MainLayout/>,孩子们: [{ 路径:'登录',元素:<登录/>},{ 路径:'注册',元素:},{ 路径:'404',元素:<NotFound/>},{ path: '/', element:
解决方案
用 withRouter
包裹你的 Reset
组件 (https://reactrouter.com/web/api/withRouter)
I seem to have a problem on my React Frontend I am working on my Reset.js page and I keep getting an error as
It happens as soon as I route to the Reset.js page and how this was working is that when a User forgets their password they are sent an email in order to Reset their password using jwt and when the link is clicked on the email it would route you to the Reset.js page and this is where you will fill in credentials to reset your password.
But in the process when the route is reached I get a TypeError: Cannot read property 'params' of undefined
Error and this is the affected React js line of code shown below.
14 | const { password1, password2, textChange, token } = formData;
15 |
16 | useEffect(() => {
> 17 | let token = match.params.token // **Error is caused here Cannot read property 'params' of undefined**
| ^ 18 | if(token) {
19 | setFormData({...formData, token,})
20 | }
This is also a screenshot to the Chrome Error for easy viewing.
And here is the full code for my Reset.js page in React.
import React, { useState, useEffect } from 'react';
import authSvg from '../assets/reset.svg';
import { ToastContainer, toast } from 'react-toastify';
import axios from 'axios';
const Reset = ({match}) => {
const [formData, setFormData] = useState({
password1: '',
password2: '',
token: '',
textChange: 'Submit'
});
// eslint-disable-next-line no-unused-vars
const { password1, password2, textChange, token } = formData;
useEffect(() => {
let token = match.params.token // **Error is caused here Cannot read property 'params' of undefined**
if(token) {
setFormData({...formData, token,})
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
const handleChange = text => e => {
setFormData({ ...formData, [text]: e.target.value });
};
const handleSubmit = e => {
console.log(password1, password2)
e.preventDefault();
if ((password1 === password2) && password1 && password2) {
setFormData({ ...formData, textChange: 'Submitting' });
axios
.put(`${process.env.REACT_APP_API_URL}/password/reset`, {
newPassword: password1,
resetPasswordLink: token
})
.then(res => {
console.log(res.data.message)
setFormData({
...formData,
password1: '',
password2: ''
});
toast.success(res.data.message);
})
.catch(err => {
toast.error('Something is wrong try again');
});
} else {
toast.error('Passwords don\'t matches');
}
};
return (
<div className='min-h-screen bg-gray-100 text-gray-900 flex justify-center'>
<ToastContainer />
<div className='max-w-screen-xl m-0 sm:m-20 bg-white shadow sm:rounded-lg flex justify-center flex-1'>
<div className='lg:w-1/2 xl:w-5/12 p-6 sm:p-12'>
<div className='mt-12 flex flex-col items-center'>
<h1 className='text-2xl xl:text-3xl font-extrabold'>
Reset Your Password
</h1>
<div className='w-full flex-1 mt-8 text-indigo-500'>
<form
className='mx-auto max-w-xs relative '
onSubmit={handleSubmit}
>
<input
className='w-full px-8 py-4 rounded-lg font-medium bg-gray-100 border border-gray-200 placeholder-gray-500 text-sm focus:outline-none focus:border-gray-400 focus:bg-white'
type='password'
placeholder='password'
onChange={handleChange('password1')}
value={password1}
/>
<input
className='w-full mt-5 px-8 py-4 rounded-lg font-medium bg-gray-100 border border-gray-200 placeholder-gray-500 text-sm focus:outline-none focus:border-gray-400 focus:bg-white'
type='password'
placeholder='Confirm password'
onChange={handleChange('password2')}
value={password2}
/>
<button
type='submit'
className='mt-5 tracking-wide font-semibold bg-indigo-500 text-gray-100 w-full py-4 rounded-lg hover:bg-indigo-700 transition-all duration-300 ease-in-out flex items-center justify-center focus:shadow-outline focus:outline-none'
>
<i className='fas fa-sign-in-alt w-6 -ml-2' />
<span className='ml-3'>Submit</span>
</button>
</form>
</div>
</div>
</div>
<div className='flex-1 bg-indigo-100 text-center hidden lg:flex'>
<div
className='m-12 xl:m-16 w-full bg-contain bg-center bg-no-repeat'
style={{ backgroundImage: `url(${authSvg})` }}
></div>
</div>
</div>
;
</div>
);
};
export default Reset;
I also tried to fix it by adding useParams
though it didn't seem to workout as planned but this is the fix I tried making and didn't workout so I decided to reach out for some help,
This is what I had tried out below;
import { useParams } from 'react-router-dom';
import jwt from 'jsonwebtoken'; //added this because of the way I was using jwt.decode
textChange: 'Submit'
});
// eslint-disable-next-line no-unused-vars
const { password1, password2, textChange } = formData; //I removed token from here since we were calling it on line 21 in the params below
// const { password1, password2, textChange, token } = formData; //this is the original code format and the one above is what I edited.
const { token } = useParams();
useEffect(() => {
let password = jwt.decode(token); //added jwt.decode(token) here though at first it was match.params.token
// let token = match.params.token
if(token) {
setFormData({...formData,password, token,}) //added password here tho it wasnt supposed to be their as reference to the original code.
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
The Error Displayed when I tried out the above code with useParams read as in the Chrome console.
Below is the Error but in a Screenshot form for easy viewing but its the same as the one above.And then below are the routes i was using for my Reset.js Page
import { Navigate } from 'react-router-dom';
import DashboardLayout from 'src/components/DashboardLayout';
import MainLayout from 'src/components/MainLayout';
import Account from 'src/pages/Account';
import CustomerList from 'src/pages/CustomerList';
import AssistantList from 'src/pages/AssistantList';
import MarketList from 'src/pages/MarketList';
import Dashboard from 'src/pages/Dashboard';
import Login from 'src/pages/Login';
import NotFound from 'src/pages/NotFound';
import ProductList from 'src/pages/ProductList';
import Register from 'src/pages/Register';
import Settings from 'src/pages/Settings';
import Activate from 'src/pages/Activate';
import Forget from 'src/pages/Forget';
import Reset from 'src/pages/Reset'; //This is how I imported my Reset.js Page
const routes = [
{
path: 'app',
element: <DashboardLayout />,
children: [
{ path: 'account', element: <Account /> },
{ path: 'assistants', element: <AssistantList /> },
{ path: 'customers', element: <CustomerList /> },
{ path: 'dashboard', element: <Dashboard /> },
{ path: 'markets', element: <MarketList /> },
{ path: 'products', element: <ProductList /> },
{ path: 'settings', element: <Settings /> },
{ path: '*', element: <Navigate to="/404" /> }
]
},
{
path: '/',
element: <MainLayout />,
children: [
{ path: 'login', element: <Login /> },
{ path: 'register', element: <Register /> },
{ path: '404', element: <NotFound /> },
{ path: '/', element: <Navigate to="/app/dashboard" /> },
{ path: '*', element: <Navigate to="/404" /> },
{ path: '/users/activate/:token', element: <Activate /> },
{ path: '/users/password/forget', element: <Forget /> },
{ path: '/users/password/reset/:token', element: <Reset /> } //Here is how I routed my reset.js page
]
}
];
export default routes;
解决方案
Wrap your Reset
component with withRouter
(https://reactrouter.com/web/api/withRouter)
这篇关于REACT JS:TypeError:无法读取未定义的属性“参数"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!