从其他组件调用Reactjs函数

问题描述 投票:0回答:1

我想把api函数保存在单独的页面中,但我不能从登录组件中调用登录api调用函数。

Console 错误 - TypeError._services__WEBPACK_IMPORTED_MODULE_3__.UseApi.Login 不是函数。_services__WEBPACK_IMPORTED_MODULE_3__.UseApi.Login不是一个函数。

//services
export const UseApi = () => {
    const Login = (email, password) => {
        axios.post('/api/login', { email: email, password: password})
           .then((result) => {
           });
    }
}


// login component
import { UseApi } from "./services" ;
const Login = () => {
    const handleSubmit = (event) => {
        UseApi.Login(email, password) 
    }
}
reactjs api components
1个回答
1
投票

useApi 是一个函数与另一个函数 Login 内定义的函数。

要么返回来自 useApi 功能

export const UseApi = () => {
    return (email, password) => {
        axios.post('/api/login', { email: email, password: password})
           .then((result) => {
                // code
           });
    }
}

称之为 UseApi()(email, password)

或者直接删除嵌套函数

export const UseApi = (email, password) => {
     axios.post('/api/login', { email: email, password: password})
     .then((result) => {
          // code
      });

}

称之为 UseApi(email, password)

另一种方法可以是返回一个来自 UseApi 函数,其中包含 login 功能

export const UseApi = () => {
    return {
        login: (email, password) => {
          axios.post('/api/login', { email: email, password: password})
            .then((result) => {
                // code
            });
        }
    }
}

称之为 UseApi().login(email, password)

© www.soinside.com 2019 - 2024. All rights reserved.