Возникли проблемы при передаче функции через компонент с помощью API контекста в Next. js - PullRequest
0 голосов
/ 21 апреля 2020

Я создаю приложение реакции, используя Next. js и пытаюсь использовать Context API для управления состоянием. Проходя через состояние в порядке - но я не могу получить доступ к функции входа в компоненте Auth, не уверен, почему он не проходит через ...

Мое хранилище контекста:

import { createContext, useReducer} from 'react';
import AppReducer from './AppReducer';


// Inital State
const initialState = {
  authenticated: false,
  authData: null,
  user: null,
  video: null,
  comment: null
}

// Create context
export const GlobalContext = createContext(initialState);

// Provider Component
export const GlobalProvider = ({ children }) => {

  const [state, dispatch] = useReducer(AppReducer, initialState)

  // Actions
  const login = (email, password) => {
    console.log('login function called')
  }

  return (
    <GlobalContext.Provider value={{
      authenticated: state.authenticated,
      login: login
    }}>
      {children}
    </GlobalContext.Provider>
  )
}

Компонент аутентификации:

import {useRef, useContext} from 'react';
import { GlobalContext } from '../context/GlobalState';
import Layout from '../components/Layout';


const Auth = () => {

  // Connect to our global state
  const { login } = useContext(GlobalContext); 

  // Create refs
  const emailRef = useRef();
  const passwordRef = useRef();

  const submitHandler = (e) => {
    e.preventDefault();

    const email = emailRef.current.value;
    const password = passwordRef.current.value;

    if (email.trim().length === 0 || password.trim().length === 0){
      return;
    }

    // Call action creator to fetch a token from the API and change the global state using a reducer
    login(email, password);

  };

  return (
    <Layout>
      <section id="auth" className="container">
        <h1>Login</h1>
        <form onSubmit={submitHandler}>
          <div className="form-control">
            <label htmlFor="email">Email</label>
            <input type="email" id="email" ref={emailRef}/>
          </div>
          <div className="form-control">
            <label htmlFor="password">Password</label>
            <input type="password" id="password" ref={passwordRef}/>
          </div>
          <button type="submit">Login</button>

        </form>
      </section>
    </Layout>
  )
};

export default Auth;

_app. js

import { GlobalProvider } from '../context/GlobalState';


function MyApp({ Component, pageProps }) {
  return (
  <GlobalProvider>
    <Component {...pageProps} />
  </GlobalProvider>
  )
}

export default MyApp;

Ошибка:

ReferenceError: логин не определен submitHandler ./pages/auth.js: 29

  26 |    }
  27 | 
  28 |    // Call action creator to fetch a token from the API and change the global state using a reducer
> 29 |    login(email, password)
     | ^  30 | 
  31 |    console.log(email, password);
  32 |

Что мне здесь не хватает? Спасибо!

...