亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

React JS:未捕獲類型錯誤:getState 不是函數

React JS:未捕獲類型錯誤:getState 不是函數

慕雪6442864 2023-07-06 16:58:25
我正在嘗試創建一個對服務器的簡單 API 調用。為了做到這一點,我創建了一個名為 - 的文件likes.js,其中包含:import axios from 'axios';import tokenConfig from './auth';// Like Reportexport 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 functionexport 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
查看完整描述

1 回答

?
蠱毒傳說

TA貢獻1895條經驗 獲得超3個贊

看來您正在使用react-reduxandredux-thunk是likePostas一個異步操作創建者。


您不需要likePostas自己調用操作創建者,而是需要使用它所采用的兩個參數(即和 )react-redux的值來調用它。目前的問題是,當您自己調用操作創建者時,并且未定義,因為您從未將這些參數傳遞給.dispatchgetStatelikePostasdispatchgetStatelikePostas


解決方案

添加一個onClick監聽器BtnWrap2,將調度likePostas動作創建者。


useDispatch從包中導入鉤子react-redux。


import { useDispatch } from "react-redux";

然后使用此鉤子在單擊按鈕時useDispatch調度操作。likePostas


const dispatch = useDispatch();


const handleClick = (id) => {

? ?dispatch(likePostas(id));

};?

并將其添加到組件handleClick上的單擊偵聽器BtnWrap2。


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


查看完整回答
反對 回復 2023-07-06
  • 1 回答
  • 0 關注
  • 170 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號