簡體   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