我们如何一次使用两个获取请求

问题描述 投票:0回答:1

我正在尝试使用 REST API 对模型进行预测,并使用 React 在前端显示输出。

如果预测是

1
,那么我需要使用条件渲染来显示第二个预测。 当我尝试一次使用两个获取请求时,它不起作用。怎么做

  const [solutestate, setSoluteState] = useState("");
  const [solventstate, setSolventState] = useState("");
  const [textstate, settextstate] = useState("");
  const [fetchData, setFetchData] = useState("");
  const [fetchDatatwo, setFetchDatatwo] = useState("");

  const [Error, setError] = useState(null);

  const onSubmit = (e) => {
    e.preventDefault(); // <-- prevent the default form action

    const formData = new FormData();
    formData.set("text_input", textstate); // <-- local component state
    console.log({ textstate });

    const formDatatwo = new FormData();
    formDatatwo.set("solute", solutestate); // <-- local component state
    formDatatwo.set("solvent", solventstate);

    fetch("http://127.0.0.1:3000/predict", {
      method: "post",
      body: formData,
    })
      .then((res) => res.json())
      .then((result) => {
        setFetchData(result.result);
      })
      .catch((err) => {
        setError(err.error);
        console.log(err);
      });

    fetch("https://flask-api-test1.herokuapp.com/predict", {
      method: "post",
      body: formDatatwo,
    })
      .then((res) => res.json())
      .then((result) => {
        setFetchData(result.result.predictions);
      })
      .catch((err) => {
        setError(err.error);
        console.log(err);
      });
  };
python reactjs fetch-api conditional-rendering
1个回答
2
投票

您可以使用 Promise.all 方法同时获取多个 api。

const firstFetch = await fetch('firstUrl');
const secondFetch = await fetch('secondUrl');

const [firstResponse, secondResponse] = Promise.all([firstFetch, secondFetch])
© www.soinside.com 2019 - 2024. All rights reserved.