javascript - 如何在 React 中返回 Axios Post 的响应?
问题描述
我有一个小问题。
我在 ReactJS 中有一个 post 函数(完全工作)。我想在这个函数之外得到它的响应,就在我调用它的地方。我怎样才能做到这一点?
async function confereInicial(idAluno,idDisciplina){
return await Axios.post("http://localhost:3001/api/check",{
idAluno: idAluno,
idDisciplina: idDisciplina}).then((response)=> {
});
}
//please ignore the way I call and read my function. it's confusing but I just wanna console.log the data outside my function. ignore the map etc
return (
<div>
{
dados.state.nodesPadrao.map(p => {
confereInicial(1,p.id).then(data => console.log(data)); //how should I do that?
app.post("/api/check",(req,res) => {
const idAluno = req.body.idAluno;
const idDisciplina = req.body.idDisciplina;
const sqlSelect = "SELECT * FROM `disciplinas_feitas` WHERE id_aluno = ? AND id_disciplina = ?;"
db.query(sqlSelect,[idAluno,idDisciplina],(err,result) => {
res.send(result);
});
});
解决方案
这应该对你有用,你可以把它放到一个变量中,当你没有从它返回一个有效的 JSX 元素时,你不需要把它放到一个 map 函数中。
const dataArray = [];
async function confereInicial(idAluno, idDisciplina) {
return axios.post("http://localhost:3001/api/check", {
idAluno: idAluno,
idDisciplina: idDisciplina
});
}
const getData = () => {
dados.state.nodesPadrao.forEach(async (p) => {
const i = await confereInicial(1, p.id);
console.log("ITEM", i);
dataArray.push(i);
});
};
useEffect(() => {
getData(); // can be called onClick or anywhere you want (make sure don't call on each re-render)
}, []);
console.log(dataArray);
推荐阅读
- php - 使用 Php 用一个锚标签替换两个/三个单词
- transactions - 托管支付页面交易返回“错误:302”
- javascript - CK Editor(经典编辑器)从父组件更新数据
- mysql - SQLAlchemy ORM 查询加入聚合子查询
- r - 如何通过将条形图位置映射到原始图的比例,将条形图覆盖在具有不同几何形状的其他图之上
- javascript - 使用手风琴表格形式解析 php 中的嵌套 json 数据
- javascript - Vue JS 中 axios 的 Slack API CORS 错误
- javascript - 如何将列表数据保存在本地存储中
- spring-boot - 在 spring-boot application.yaml 中从其他地方引用配置部分
- c# - 实现 IEnumerator 时如何强输入“Current”