如何获取导入函数来设置功能组件的状态?

How to get imported functions to set state of functional component?

我有一个 React class 组件,它带有相当冗长的 onSubmit 函数,我已将其放入另一个文件以保持代码更整洁。

我尝试将 class 组件转换为功能组件,用 useState 替换了我的所有状态和 setState 函数,但现在我的 useState 状态更新程序在导入函数中返回未定义。我可以使用带有功能组件的导入功能来更新状态吗?当该函数被导入 class 组件并且我的状态更新程序是 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

中未定义

谢谢!

您需要先将 setAuthenticated 函数传递给 loginUser 函数,然后再调用它。

return 来自您的登录用户挂钩的 onSubmiHandler 函数。


const doLogin = (email , password) => {

  /// your code here

}

return {doLogin}

然后在你的主要组件中使用 doLogin 函数

  //inside functional component

  const {doLogin} = loginUser();

  
  onSubmit = () => doLogin(email, password)

有关更多信息,您可以在此处查看如何使用自定义挂钩

https://reactjs.org/docs/hooks-custom.html

开始 loginUser 无法知道您插入的 setState 尝试将其作为参数传递,它会修复它

我看到的另一个问题是您使用了 this 关键字,而在功能组件中您只使用了 props.

只是为了让你知道不要传递 null 作为初始值传递空字符串、数字等。 更新

这也是您将 setState 作为参数传递的方式

 loginUser((e)=>setEmail(e)) 

实现这一点的一种方法是将所有设置方法作为参数传递给 loginUser 函数。

但更好的方法是:

创建两个单独的文件

1 用于登录 api 调用如下:

login.js

function login(email, password){
    const login = await axios.post('http://localhost:5000/api/v1/auth/login', {
        email,
        password
    });
    return login.data;
}

另一个用于获取数据

getProfile.js

function getProfile(token){
    const options = {
        headers: {
            Authorization: `Bearer ${token}`
        }
    };
    const getUser = await axios.get(
        'http://localhost:5000/api/v1/auth/me',
        options
    );
    return getUser.data;
}

现在你在实际组件提交调用函数中设置状态的东西吗

const _handleSubmit = async (e) => {
    e.preventDefault();
    const token = await login(email, password);
    const user = await getProfile(token);
    if (user) {
        console.log(user);
        props.onHandleUser(user);
        setAuthenticated(true);
        setUser(getUser.data.data);
        setEmail('');
        setPassword('');

        localStorage.setItem('user', JSON.stringify(user));
        console.log(localStorage.getItem('user'));
    }
};