我正在尝试创建一个对服务器的简单 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
蛊毒传说
相关分类