刚把react从v16更新到v17,得到了错误,编译失败。
Line 37:9: React Hook "Api.useAuth" is called conditionally. React Hooks must be called in the exact same order in every component render react-hooks/rules-of-hooks
Line 47:9: React Hook "Api.useAuth" is called in function "loginInApp" that is neither a React function component nor a custom React Hook function. React component names must start with an uppercase letter react-hooks/rules-of-hooks
我的代码如下
import Api from 'utils/api';
// AuthContext.Provider
const AuthProvider = (props: any) => {
if (existingToken) {
Api.useAuth(existingToken);
}
... other code
const loginInApp = (token: string) => {
Api.useAuth(token);
};
}
在/utils/api中
class Api {
... other code
useAuth = (token: string) => {
this.axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
};
}
const api = new Api();
export default api;
我完全不明白,为什么会这样,我应该怎么做。
发布于 2021-01-20 12:02:59
当eslint
想要检查Hooks rules
时,它不会理解您的类或其他方法,并且不会尝试这样做,因为这是一个繁重的过程。它只是检查你的方法是否以use
开头。只需更改您的类方法名称,您就可以开始了:
class Api {
... other code
auth = (token: string) => {
this.axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
};
}
https://stackoverflow.com/questions/65809068
复制