首页 > 解决方案 > 使用带有上下文的 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

我如何使用状态并将它们调用到登录组件中?

标签: reactjsreact-hooksreact-context

解决方案


Yu 可以像现在一样使用 react 方法(hooks),只要确保你当前正在导入东西。我认为您的上层文件中存在导入错误,使用应该使用

import {useState} from 'react'

并保持您的代码相同或将每个替换useStateReact.useState.


推荐阅读