【发布时间】:2021-01-06 08:45:15
【问题描述】:
我有一个带有相当长的 onSubmit 函数的 react 类组件,我已将其放入另一个文件中,以使代码更整洁。
我尝试将类组件转换为功能组件,用 useState 替换我的所有 state 和 setState 函数,但现在我的 useState 状态更新程序在导入的函数中返回 undefined。我可以使用带有功能组件的导入函数来更新状态吗?该函数在导入到类组件时运行良好,并且我的状态更新器是 setState();
//Imported function in utils.js
export const loginUser = async function (email, password) {
try {
const login = await axios.post('http://localhost:5000/api/v1/auth/login', {
email,
password
});
const options = {
headers: {
Authorization: `Bearer ${login.data.token}`
}
};
const getUser = await axios.get(
'http://localhost:5000/api/v1/auth/me',
options
);
const user = getUser.data.data;
setAuthenticated(true);
setUser(getUser.data.data);
setEmail('');
setPassword('');
localStorage.setItem('user', JSON.stringify(user));
console.log(localStorage.getItem('user'));
} catch (err) {
console.log(err);
}
};
// Functional component with imported function
import React, { useState } from 'react';
import axios from 'axios';
import PropTypes from 'prop-types';
import { Login } from './Login';
const { loginUser } = require('../utils/utils');
export const Splash = () => {
const [user, setUser] = useState(null);
const [error, setError] = useState(null);
const [authenticated, setAuthenticated] = useState(false);
const [msg, setMsg] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const _handleEmail = (e) => {
setEmail(e.target.value);
};
const _handlePass = (e) => {
setPassword(e.target.value);
};
const _handleSubmit = async (e) => {
e.preventDefault();
loginUser(email, password);
if (user) {
console.log(user);
this.props.onHandleUser(user);
}
};
return (
<div className='splashStyle'>
{!authenticated && (
<Login
handleEmail={_handleEmail}
handlePass={_handlePass}
handleSubmit={_handleSubmit}
isAuthenticated={authenticated}
/>
)}
</div>
);
};d
编辑:我的问题是 setAuthenticated、setUser、setEmail 和 setPassword 在 utils.js 中未定义
谢谢!
【问题讨论】:
-
通常在应用程序中,用户登录后,他们希望重定向到另一个页面。为什么在您的情况下没有重定向功能?以及为什么在提交表单后需要重新初始化邮箱和密码。提交表单后,表单没有任何用途。
标签: reactjs state react-functional-component