首页 > 解决方案 > 它是获取多个api的正确方法吗

问题描述

我必须获取两个 api,所以我创建了两个函数并通过在另一个函数中调用这两个方法来同时调用它们,如下面的代码所示。我不确定这是否是这样做的方法,还是应该将它们都放在 componentDidMount 中?另外我如何绑定textarea的字数?我使用 textlen 来计算单词,但我不知道如何使用 textlen 在底部的段落元素中显示它

以下是代码,请指导我正确的方向。我想我快到了,但还没有完全搞定最后一块拼图

import React, { Component } from "react";
import { Button } from "react-bootstrap";

export default class MainText extends Component {
  constructor(props) {
    super(props);
    this.state = {
      title: "",
      id: null,
      snippetDescription: "",
      scoredata: null,
      marksdata: null,
      textlen: 0,
    };
  }

  scoreanalysis = (snippetDescription, textlen) => {
    fetch("api/scores/", {
      method: "POST",
      body: JSON.stringify({
        snippetdesc: "snippetDescription"
      }),
      headers: {
        "Content-type": "application/json; charset=UTF-8"
      }
    })
      .then(response => response.json())
      .then(
        textdata => {
          this.setState({
            scoredata: textdata.scores,
            textlen: snippetDescription.split(" ").length
          });
        },
        error => {
          console.log(error);
        }
      );
  };

  sportsanalysis = snippetDescription => {
    fetch("api/sports", {
      method: "POST",
      body: JSON.stringify({
        snippetdesc: "snippetDescription"
      }),
      headers: {
        "Content-Type": "application/json; charset=UTF-8"
      }
    })
      .then(response => response.json())
      .then(
        sportsdata => {
          this.setState({
            marksdata: sportsdata.data
          });
        },
        error => {
          console.log(error);
        }
      );
  };

  analyse = (this.state) => {
    try {
      this.scoreanalysis(snippetDescription, textlen).bind(this);
      this.sportsanalysis(snippetDescription).bind(this);

    } catch (error) {
      console.log("An error has occured while fetching data");
    }


  render() {
    return (
      <>
             <input
                type="text"
                id="titletext"
                onChange={title => this.setState({ title })}
              ></input>
            <textarea
              onChange={snippetDescription =>
                this.setState({ snippetDescription })
              }
            ></textarea>

            <Button onClick={() => this.analyse({ ...this.state })}> Analyse </Button>

            <p>{this.state.textlen} Words</p>
</>
)}
}

标签: javascriptreactjsapifetch

解决方案


您不能将 api 的函数调用放入 componentDidMount() 因为您在单击按钮时执行它们

不要忘记在你的 api 函数调用中添加一个 return

  sportsanalysis = snippetDescription => {
    return fetch("api/sports", { // return HERE !!!!!!!!!!!
      method: "POST",
      body: JSON.stringify({
        snippetdesc: "snippetDescription"
      }),
      headers: {
        "Content-Type": "application/json; charset=UTF-8"
      }
    })
      .then(response => response.json())
      .then(
        sportsdata => {
          this.setState({
            marksdata: sportsdata.data
          });
        },
        error => {
          console.log(error);
        }
      );
  };

您可以像这样在 try catch 中使用 await 。

analyse = async (this.state) => { // async here !!!
    try {
      await this.scoreanalysis(snippetDescription, textlen); // await here no need to bind
      await this.sportsanalysis(snippetDescription); // await here no need to bind
    } catch (error) {
      console.log("An error has occured while fetching data");
    }
}

推荐阅读