如何在包装在HOC中的组件内使用useContext()钩子?

时间:2019-06-07 04:15:16

标签: reactjs react-hooks react-context

我有一个Login组件和一个App组件。 App组件在上下文提供程序中包含Login组件。 Login组件又由withFormik高阶组件包装,用于表单验证。当我尝试在Login组件中使用useContext()挂钩时,它无法编译并显示以下错误:

./ src / components / login / Login.jsx

第12行:在函数“登录”中调用React Hook“ useContext”,该函数既不是React函数组件也不是自定义的React Hook函数react-hooks / rules-of-hooks

也尝试过React文档,但无法解决。 :(

Login.jsx:

import React, { useContext } from 'react';
import { withFormik, Form, Field } from 'formik';

import { RenderInput, RenderMobileNumberInput } from '../../utils/input.util';
import { isMobile, isPassword } from '../../utils/validation.util';

import AuthContext from '../../store/auth.store';

import '../../styles/login.scss';

const login = props => {
  const authContext = useContext(AuthContext);
  console.log('authContext', authContext);

  return (
    <div className="login-container">
      <div className="login-content">
        <h1 className="header">Agent Login</h1>
        <div className="login-form">
          <Form>
            <div className="input-row">
              <label htmlFor="mobile">Mobile Number</label>
              <Field
                component={RenderMobileNumberInput}
                countrycode="+91"
                name="mobile"
                placeholder="Mobile Number"
                validate={isMobile}
              />
            </div>
            <div className="input-row">
              <label htmlFor="password">Password</label>
              <Field
                type="password"
                component={RenderInput}
                name="password"
                placeholder="Enter Password"
                validate={isPassword}
              />
            </div>
            <button className="btn btn-yellow" type="submit">
              Login
            </button>
          </Form>
        </div>
      </div>
    </div>
  );
};

const FormikApp = withFormik({
  mapPropsToValues(props) {
    return {
      mobile: props.mobile || '',
      password: props.password || '',
    };
  },
  handleSubmit(values) {
    console.log(values);
  },
})(login);

export default FormikApp;

App.jsx:

// Importing required NPM modules
import React from 'react';
import { withRouter, Switch, Route } from 'react-router-dom';

// Importing local modules & components
import Login from './components/login/Login';

import AuthContext from './store/auth.store';

// Impoting stylesheets
import './App.scss';

function App() {
  return (
    <AuthContext.Provider value={‌{ isAuthenticated: false }}>
      <div className="App">
        <Switch>
          <Route path="/" exact component={Login} />
        </Switch>
      </div>
    </AuthContext.Provider>
  );
}

export default withRouter(App);

auth.store.js:

import { createContext } from 'react';

const initialContext = {
  user: null,
  isAuthenticated: false,
};

const authContext = createContext({ ...initialContext });

export default authContext;

index.js:

/* eslint-disable react/jsx-filename-extension */
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';

import './index.scss';
import App from './App';
import * as serviceWorker from './serviceWorker';

// Importing store contexts
import AuthContext from './store/auth.store';

ReactDOM.render(
  <BrowserRouter>
    <AuthContext.Provider value={{}}>
      <App />
    </AuthContext.Provider>
  </BrowserRouter>,
  document.getElementById('root')
);

serviceWorker.unregister();

1 个答案:

答案 0 :(得分:0)

错误确切说明了需要/想要说的内容。挂钩只能在React功能组件内部调用。 https://reactjs.org/docs/hooks-rules.html

在将login组件编写为功能组件时,请用withForm HOC包装它,将其转换为类组件。您应该阅读withFormik源代码才能看到它:https://github.com/jaredpalmer/formik/blob/next/src/withFormik.tsx

基本上,withFormik HOC所做的事情(以及许多其他HOC都做同样的事情)是将您的组件包装在类组件中。这样做是为了将其他道具(通常称为injected props)传递给您的组件。

要解决您的问题,应避免将withFormik HOC与react挂钩一起使用。您可以选择使用Formik组件而不是withFormik HOC。