reactjs - 使用带有上下文的 React Hook
问题描述
我做了一个小登录页面。我想分离视图和控制器。所以我使用上下文
const axios = require('axios');
const AuthContext = React.createContext()
const onLogin = (login, password, saveCredentials) => {
const [error, setError] = useState("");
const [authentified, setAuthentified] = useState("");
axios.post('/signin', {
username: login,
password: password
})
.then(function(response) {
if (saveCredentials)
{
var cred = {
user: response.data.username,
password: response.data.password
};
}
console.log("test : " + response);
setAuthentified(true) ;
})
.catch(function (err) {
setError(err.response.data.message);
})
}
const AuthProvider = props =>
(
<AuthContext.Provider
value={{
onLogin
}}>
{props.children}
</AuthContext.Provider>
);
export { AuthProvider, AuthContext };
意见:
import { AuthContext } from 'controllers/authContext'
export default function Login(props) {
const classes = useStyles();
const Auth = useContext(AuthContext);
...
{ !Auth.authentified ? (
<Button simple size="lg" color="primary" onClick={() => Auth.useLogin(login, password)}>Login</Button>
</CardFooter>
<p align="center">{Auth.error}</p>
) : null
但我不能将状态用于上下文函数,它不是反应函数。错误信息是:React Hook "useState" is called in function "onLogin" which is neither a React function component or a custom React Hook function react-hooks/rules-of-hooks
我如何使用状态并将它们调用到登录组件中?
解决方案
Yu 可以像现在一样使用 react 方法(hooks
),只要确保你当前正在导入东西。我认为您的上层文件中存在导入错误,使用应该使用
import {useState} from 'react'
并保持您的代码相同或将每个替换useState
为React.useState
.
推荐阅读
- angular - 在 Azure 中托管时,Angular 应用程序刷新不起作用
- javascript - Vue.js 附加多个类
- machine-learning - 这是过拟合的例子吗?
- ruby-on-rails-4 - Redirect_to 声称可以工作,但实际上并没有在浏览器中发生
- wix - Windows 安装程序:哪些文件被视为“版本化”
- android - 在手机上运行应用程序失败(Android Studio)
- java - 来自 Android 的“网络无法访问”,但在 Python 客户端上运行良好
- parsing - 在 LUA 中解析字符串
- java - 从 Java 调用存储过程
- java - 为什么 compareTo BigInteger while 循环不退出?