【问题标题】:React-Typescript: Expected an assignment or function call and instead saw an expressionReact-Typescript:期望一个赋值或函数调用,而是看到一个表达式
【发布时间】:2022-01-14 05:08:56
【问题描述】:

我正在使用 React 和 Redux 进行注册,并且我已经完成了我需要的所有操作和 reduser,但是我收到了这个错误:

Expected an assignment or function call and instead saw an expression 

这个文件是一个 Action Creator,通过它我使用 Dispatch 与 Reducer 进行通信。

auth.ts:(动作创建者)

export const signupActionCreator = (
  email: string,
  name: string
) => {
  return async (dispatch: Dispatch<UserTypes>) => {
    return AuthService.signup(email, name)
      .then((res) => {
        // tttt
        localStorage.setItem('token', res.data)
        dispatch({
          type: Types.SIGNUP,
          // payload: res.data.message,
          // tttt
          payload: res.data  
        });

        return Promise.resolve();
      })
      .catch((err) => {
        console.log(err);
        return Promise.reject();
      });
  };
};

这是文件,我为每个操作使用了一个类型,我使用了 Enum。

types.ts:

export enum Types {
  SIGNUP = "SIGNUP"
}

通过这个文件,我能够与后端进行通信。

authServices.ts:

import API_URL from "../http-common";
import axios from "axios";

const signup = (email: string, name: string) => {
  return axios.post(API_URL + "/authentication/sign-up", { email, name });
};
const AuthService = {
  signup,
};

export default AuthService;

通过这个文件我可以定义接口。

auth.d.ts:

export interface UserData {
    name: string;
    email: string;
}

export interface UserState {
    data: UserData[];
}

export interface UserAction {
    type: string;
    payload: any;
}

export type UserTypes = UserAction;

【问题讨论】:

  • 你从哪里得到错误?您在哪里调用动作创建器?

标签: reactjs typescript redux


【解决方案1】:

你只需要从signupActionCreator返回这个:

export const signupActionCreator = (email: string, name: string) => {
  return async (dispatch: Dispatch<UserAction>) => {

或将其分配给变量:

export const signupActionCreator = (email: string, name: string): void => {
  const testVariable = async (dispatch: Dispatch<UserAction>) => {

【讨论】:

  • 我按照你说的修改了帖子,修改了代码,但问题还是一样。
  • 你能把它放在沙箱里吗(比如代码沙箱)?当我自己尝试时,它解决了问题。
【解决方案2】:

我阅读了这篇文章并了解导致问题的原因:

https://www.codecademy.com/forum_questions/505a2f774f0e7400020021ba

我跟踪了我的代码,发现问题出在 authServices,ts 文件中,我必须分配变量“response”,然后返回变量“response”。

async function signup(email: string, name: string) {
  const response = await axios.post(API_URL + "/authentication/sign-up", { email, name });
  return response;
};

然后我的问题就解决了。

【讨论】:

    猜你喜欢
    • 2020-02-12
    • 2019-10-15
    • 1970-01-01
    • 2021-04-12
    • 2021-05-20
    • 2017-09-09
    • 2021-04-19
    • 1970-01-01
    相关资源
    最近更新 更多