首页 > 解决方案 > 如何在 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);
    });

});

有人可以帮帮我吗?

标签: javascriptreactjsaxios

解决方案


这应该对你有用,你可以把它放到一个变量中,当你没有从它返回一个有效的 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);

推荐阅读