[英]React static class/method call and Network call
I am relatively new in React but I am trying to create a class/method for network call.我在 React 中相对较新,但我正在尝试为网络调用创建一个类/方法。 Nothing complex just a way to make the code readable.没有什么复杂的,只是一种使代码可读的方法。
I have a class:我有一个 class:
class Auth {
getToken(username, password) {
const endpointOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: `${username}`, password: `${password}` })
};
fetch(`${Constant.BASE_WP_URL}${Constant.TOKEN_ENDPOINT}`, endpointOptions)
.then(async response => {
const data = await response.json();
if (!response.ok) {
// get error message from body or default to response status
const error = (data && data.message) || response.status;
throw error;
}
return data;
})
.catch(error => {
throw error;
});
}
}
export default Auth;
I am trying to call it using:我正在尝试使用以下方法调用它:
import Auth from '../../data/network/Auth';
requestSignIn = (event) => {
event.preventDefault();
this.setState({loading: true})
try {
const authData = Auth.getToken(`${this.state.email}`, `${this.state.password}`);
sessionStorage.setItem('authToken', authData.token)
} catch (error) {
console.log("Connection to WP - Auth Token failed ")
console.error(error);
}
}
but React is complaining because getToken
is not a function.但 React 抱怨,因为getToken
不是 function。 I am trying to create a class Auth
to have inside all methods/functions I need related to Auth process.我正在尝试创建一个 class 身份Auth
,以包含与身份验证过程相关的所有方法/功能。
Also, is it the right way to handle the result?另外,这是处理结果的正确方法吗? is the try/catch
as done works or should I do it differently as the getToken
is an API call.是try/catch
作为 done 工作还是我应该做不同的事情,因为getToken
是一个 API 调用。
Any idea?任何想法?
pretty sure, it's easy but I can't find any interesting topics on Google.很确定,这很容易,但我在 Google 上找不到任何有趣的话题。
Thanks谢谢
In you class definition add static
in front of your function to be在你的 class 定义中添加static
在你的 function 前面
class Auth {
static async getToken(username, password) {
const endpointOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: `${username}`, password: `${password}` })
};
try {
const response = await fetch(`${Constant.BASE_WP_URL}${Constant.TOKEN_ENDPOINT}`, endpointOptions)
const data = await response.json();
if (!response.ok) {
const error = (data && data.message) || response.status;
throw error;
}
return data;
} catch (error) {
throw error
}
}
}
export default Auth;
then you will be able to call it as static function.那么您就可以将其称为 static function。
and requestSignIn
will be using it in the following code requestSignIn
将在以下代码中使用它
requestSignIn = async (event) => {
event.preventDefault();
this.setState({ loading: true })
try {
const authData = await Auth.getToken(`${this.state.email}`, `${this.state.password}`);
sessionStorage.setItem('authToken', authData.token)
} catch (error) {
console.log("Connection to WP - Auth Token failed ")
console.error(error);
}
}
I think, if you want to use function directly in OOP of JavaScript, you must put static
keyword in front of the function name
. I think, if you want to use function directly in OOP of JavaScript, you must put static
keyword in front of the function name
.
In your auth
file在您的auth
文件中
static class Auth {
static getToken(username, password) {
...
}
}
In your index
file在您的index
文件中
import Auth from '../../data/network/Auth';
const authData = Auth.getToken(`${this.state.email}`, `${this.state.password}`);
If you don't have static
in front of the function name
.如果function name
前面没有static
。 You have to create a new instance of the class Auth
in order to use the function inside.您必须创建 class Auth
的新实例才能在内部使用 function。
import Auth from '../../data/network/Auth';
const AuthInit = Auth();
authData = AuthInit.getToken(`${this.state.email}`, `${this.state.password}`);
=========================== ============================
Update for applying asynchronous method应用异步方法的更新
// ====== auth file
static class Auth {
static async getToken(username, password) {
...
// assign fetched data to data_fetch
const data_fetch = fetch(`${Constant.BASE_WP_URL}${Constant.TOKEN_ENDPOINT}`, endpointOptions)
.then(async response => {
const data = await response.json();
if (!response.ok) {
// get error message from body or default to response status
const error = (data && data.message) || response.status;
throw error;
}
return data;
})
.catch(error => {
throw error;
});
return data_fetch;
}
}
// ======= index file
import Auth from '../../data/network/Auth';
...
requestSignIn = async (event) => { // put async in front of your function
// the function outside (requestSignIn) must be async type
// in order to use await keyword for getToken() function
event.preventDefault();
this.setState({loading: true})
try {
// because your getToken function is now a async function, you can
// use "await" keyword in front of it to wait for fetching data to finish
const authData = await Auth.getToken(`${this.state.email}`, `${this.state.password}`);
sessionStorage.setItem('authToken', authData.token)
} catch (error) {
console.log("Connection to WP - Auth Token failed ")
console.error(error);
}
}
Hope this would help希望这会有所帮助
but React is complaining because getToken is not a function但 React 抱怨,因为 getToken 不是 function
You've defined getToken
as a method of an Auth
instance, not a static function.您已将getToken
定义为Auth
实例的方法,而不是 static function。 But you don't need an Auth class here at all, just use the proper exports/imports.但是您根本不需要 Auth class,只需使用正确的导出/导入即可。
replace the Auth-class with:将 Auth 类替换为:
export function getToken(username, password) {
//...
};
and you can either你可以
/// import all exports from that file under the name `Auth`
import * as Auth from '../../data/network/Auth';
// ...
const authData = Auth.getToken(...);
or或者
// import these specific exports from that file.
import { getToken } from '../../data/network/Auth';
// ...
const authData = getToken(...);
The last option has the advantage that it can be tree-shaken.最后一个选项的优点是可以摇树。 If You have some build-process, the compiler can eliminate all the pieces of code that you don't use;如果您有一些构建过程,编译器可以消除您不使用的所有代码; especially useful for libraries.对图书馆特别有用。
Even if you want to keep the default import and import the entire thing, imo.即使您想保留默认导入并导入整个内容,imo。 it makes more sense to use a simple Object rather than a class with static methods.使用简单的 Object 而不是 class 和 static 方法更有意义。
function getToken(username, password) {
//...
}
export default {
getToken
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.