简体   繁体   English

反应上下文 API - 调度不是 function

[英]React Context API - dispatch is not a function

Implementing a Log in system with React Context API.使用 React Context API 实现登录系统。 When submitted the form with user credentials, getting an error.使用用户凭据提交表单时,出现错误。 Error:错误:

Unhandled Rejection (TypeError): dispatch is not a function
        loginCall
        src/apiCalls.js:4
          1 | import axios from "axios";
          2 | 
          3 | export const loginCall = async (userCredential, dispatch) => {
        > 4 |   dispatch({ type: "LOGIN_START" });
          5 |   try {
          6 |     const res = await axios.post("auth/login", userCredential);
          7 |     dispatch({ type: "LOGIN_SUCCESS", payload: res.data });

Files: Login.jsx文件:Login.jsx

import React, { useContext, useRef } from "react";
import bgImg from "../assets/login/tw-bg.png";
import "./styles/login.css";
import TwitterIcon from "@mui/icons-material/Twitter";
import { loginCall } from "../apiCalls";
import {AuthContext} from '../context/AuthContext'
function Login() {
  const email = useRef();
  const password = useRef();
  const context = useContext(AuthContext);
  const handleSubmit = (e) => {
    e.preventDefault();
    loginCall(
      { email: email.current.value, password: password.current.value },
      context.dispatch
    );
  };
  console.log(context.user)
  return (
    <div className="login-container">
      <div className="left">
        <TwitterIcon className="left-tw-icon" style={{ fontSize: 250 }} />
        <img src={bgImg} alt="background" className="login-background" />
      </div>
      <div className="right">
        <TwitterIcon className="right-tw-icon" color="primary" />
        <div className="main-title-container">
          <span className="main-title-span">Şu anda olup bitenler</span>
        </div>
        <div className="secondary-title-container">
          <span className="secondary-title-span">Twitter'a bugün katıl.</span>
        </div>
        <div className="form-container">
          <form onSubmit={handleSubmit}>
            <input type="email" placeholder="Username" ref={email} />
            <input type="password" placeholder="Password" ref={password} />
            <button type="submit">Log in</button>
          </form>
        </div>
      </div>
    </div>
  );
}

export default Login;

apiCalls.js apiCalls.js

import axios from "axios";

export const loginCall = async (userCredential, dispatch) => {
  dispatch({ type: "LOGIN_START" });
  try {
    const res = await axios.post("auth/login", userCredential);
    dispatch({ type: "LOGIN_SUCCESS", payload: res.data });
  } catch (error) {
    dispatch({ type: "LOGIN_FAILURE", payload: error });
  }
};

AuthContext.js AuthContext.js

import { Children, createContext, useReducer } from "react";
import AuthReducer from "./AuthReducer";

const INITIAL_STATE = {
  user: null,
  error: null,
  isFetching: false,
};

export const AuthContext = createContext(INITIAL_STATE);

export const AuthContextProvider = ({children}) => {
  const [state, dispatch] = useReducer(AuthReducer, INITIAL_STATE);

  return (
    <AuthContextProvider
      value={{
        user: state.user,
        error: state.error,
        isFetching: state.isFetching,
        dispatch,
      }}
    >
      {children}
    </AuthContextProvider>
  );
};

Any help appreciated.任何帮助表示赞赏。 Edit: AuthReducer and AuthActions added.编辑:添加了 AuthReducer 和 AuthActions。

const AuthReducer = (state, action) => {
  switch (action.type) {
    case "LOGIN_START":
      return {
        user: null,
        error: null,
        isFetching: true,
      };
    case "LOGIN_FAILURE":
      return {
        user: null,
        error: action.payload,
        isFetching: false,
      };
    case "LOGIN_SUCCESS":
      return {
        user: action.payload,
        error: null,
        isFetching: false,
      };
  }
};


export default AuthReducer
```
export const  LOGIN_START = (userCredentials) =>  {
    type:"LOGIN_START"
}

export const  LOGIN_SUCCESS = (user) =>  ({
    type:"LOGIN_SUCCESS",
    payload:user
})

export const  LOGIN_FAILURE = (err) =>  ({
    type:"LOGIN_FAILURE",
})

```

Some comment to handle "mostly code error."一些处理“主要是代码错误”的评论。 It seems all clear to me.这对我来说似乎很清楚。 But the problem still continues.但问题仍然存在。 If there is a point I am missing, it would be great to learn from you.如果有我遗漏的一点,向你学习会很棒。 Thanks in advance.提前致谢。

you can try this:你可以试试这个:

import axios from "axios";

export const loginCall = (userCredential) => {
   return async (dispatch, getState) => {
  dispatch(LOGIN_START());
  try {
    const res = await axios.post("auth/login", userCredential);
    dispatch(LOGIN_SUCCESS(res.data);
  } catch (error) {
    dispatch(LOGIN_FAILURE());
  }
};


in your error you see this message:在您的错误中,您会看到以下消息:

dispatch is not a function
        loginCall
        src/apiCalls.js:4

it is quite straight forward.这很简单。 It tells you what the problem is which dispatch.它告诉你问题是哪个调度。 it is loginCall and and loginCall is in apiCalls.它是 loginCall 并且 loginCall 在 apiCalls 中。 try to focus on the error that you see.尝试专注于您看到的错误。 dispatch basically fires the function that you want to call. dispatch 基本上会触发您要调用的 function 。 In your syntax, you put an object in the dispatch({some stuff}), but it actually expects you to call a function there.在您的语法中,您在调度中放置了 object({some stuff}),但它实际上希望您在那里调用 function。

I am not sure if my solution will fix everything but in the worst case, you should at least get a different error.我不确定我的解决方案是否能解决所有问题,但在最坏的情况下,您至少应该得到一个不同的错误。 :) :)

I had the same problem recently working on a similar project.我最近在做一个类似的项目时遇到了同样的问题。

npm install cors

then in your index.js file with your express declarations, const cors = require('cors') , then at the very top your code but below your imports, app.use(cors())然后在带有明确声明的 index.js 文件中, const cors = require('cors') ,然后在代码的最顶部但在导入的下方, app.use(cors())

That will probably fix it.那可能会解决它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM