猿问

React JS:未捕获类型错误:getState 不是函数

我正在尝试创建一个对服务器的简单 API 调用。为了做到这一点,我创建了一个名为 - 的文件likes.js,其中包含:


import axios from 'axios';

import tokenConfig from './auth';


// Like Report

export const likePostas = (report_public_id) => (dispatch, getState) => {

  console.log('Trying to call the server')

  axios

    .post(`/api/report/like?report=${report_public_id}`, tokenConfig(getState))

    .then((res) => {

      console.log(res.data)

    })

    .catch(err => {

      console.log(err.response.data)

    });

};

所以基本上它应该可以工作,另一件事是我需要将令牌传递到标头,所以我有另一个文件是auth.js


// Setup config with token - helper function

export const tokenConfig = (getState) => {

  // Get token from state

  const token = getState().auth.token;


  // Headers

  const config = {

    headers: {

      'Content-Type': 'application/json',

    },

  };


  // If token, add to headers config

  if (token) {

    config.headers['Authorization'] = `Token ${token}`;

  }


  return config;

};


export default tokenConfig;

现在我只需按 JSX 内的按钮即可调用它。这是我的代码:


import React, { useEffect, useState } from "react";

import { Button } from "../ButtonElement";

import { likePostas } from "../actions/likes";



const ReportCards = ({ report }) => {

  const IsVerifiedDiv = (

    <IsVerified>

      <GoVerified />

      <IsVerifiedToolTip>

        This user is <span style={{ color: "#01BF71" }}>Verified</span>

      </IsVerifiedToolTip>

    </IsVerified>

  );


  useEffect(() => {

    // Update the document title using the browser API

    document.title = `Winteka - View Report`;

    window.scroll({

      top: 0,

      left: 0,

      behavior: "smooth",

    });

  }, [0]);


  return (

    <>

        <BtnWrap2 onClick={likePostas(report.public_id)} />

    </>

  );

};


export default ReportCards;

但当我按下按钮时,我收到此错误:


react-dom.development.js:327 Uncaught TypeError: getState is not a function


慕雪6442864
浏览 149回答 1
1回答

蛊毒传说

看来您正在使用react-reduxandredux-thunk是likePostas一个异步操作创建者。您不需要likePostas自己调用操作创建者,而是需要使用它所采用的两个参数(即和 )react-redux的值来调用它。目前的问题是,当您自己调用操作创建者时,并且未定义,因为您从未将这些参数传递给.dispatchgetStatelikePostasdispatchgetStatelikePostas解决方案添加一个onClick监听器BtnWrap2,将调度likePostas动作创建者。useDispatch从包中导入钩子react-redux。import { useDispatch } from "react-redux";然后使用此钩子在单击按钮时useDispatch调度操作。likePostasconst dispatch = useDispatch();const handleClick = (id) => {   dispatch(likePostas(id));}; 并将其添加到组件handleClick上的单击侦听器BtnWrap2。<BtnWrap2 onClick={() => handleClick(report.public_id)} />
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答