我必须获取两个api,因此我创建了两个函数,并通过在另一个函数中调用这两个方法来同时调用它们,如下面的代码所示。我不确定这是否是这样做的方式,还是应该将它们都放在componentDidMount中?另外,如何绑定文本区域的字数?我使用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>
</>
)}
}
我必须获取两个api,因此我创建了两个函数,并通过在另一个函数中调用这两个方法来同时调用它们,如下面的代码所示。我不确定这是不是...
您无法将api的函数调用放入componentDidMount(),因为单击按钮时会执行它们