繁体   English   中英

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

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

使用 React Context API 实现登录系统。 使用用户凭据提交表单时,出现错误。 错误:

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 });

文件: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

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

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>
  );
};

任何帮助表示赞赏。 编辑:添加了 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",
})

```

一些处理“主要是代码错误”的评论。 这对我来说似乎很清楚。 但问题仍然存在。 如果有我遗漏的一点,向你学习会很棒。 提前致谢。

你可以试试这个:

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());
  }
};


在您的错误中,您会看到以下消息:

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

这很简单。 它告诉你问题是哪个调度。 它是 loginCall 并且 loginCall 在 apiCalls 中。 尝试专注于您看到的错误。 dispatch 基本上会触发您要调用的 function 。 在您的语法中,您在调度中放置了 object({some stuff}),但它实际上希望您在那里调用 function。

我不确定我的解决方案是否能解决所有问题,但在最坏的情况下,您至少应该得到一个不同的错误。 :)

我最近在做一个类似的项目时遇到了同样的问题。

npm install cors

然后在带有明确声明的 index.js 文件中, const cors = require('cors') ,然后在代码的最顶部但在导入的下方, app.use(cors())

那可能会解决它。

暂无
暂无

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

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