【发布时间】:2021-07-14 00:21:56
【问题描述】:
我正在编写一个 React 应用程序,但遇到了问题。
当我调用 HandleApiCall 函数时,我想将按钮的状态从 Write 更改为 Loading... 并且我想保留它直到我得到所有来自 Axios api 调用的数据。
我正在使用类组件
这是 JSX 代码。
<form onSubmit={this.HandleApiCall.bind(this)}>
<div className="TextAreaContainer">
{ this.state.loading === false ?
<button className= "btn_" type="submit" >Write</button> :
<button className= "btn_" type="submit">Loading...</button>
}
</div>
<div className="TextareaContainer">
<textarea
className= "textarea"
placeholder="write the description here"
value={this.state.input}
onChange={(ev) => {
this.updateBody(ev.target.value)
}
}>
</textarea>
</div>
</form>
这是 HandleApiCall 函数
HandleApiCall(e) {
e.preventDefault();
await this.setState({ loading : true });
axios.post(TRANSLATE_API_URL, body).then(({ data: { text } }) => {//some code here});
}
我尝试过这样做,但它不起作用。
有什么想法吗?
【问题讨论】:
-
在通过提交/单击执行的方法内部,会将
loading变量的状态更新为true。然后在渲染(返回)中,将做一个简单的检查this.state.loading ? //the loading button : //base button。在 axios 完成其发布/获取之后 - 使其执行另一个设置状态,将loading设置为false。会使用await,因为这可能会导致问题。另一种方法是将loading的状态设置为true,然后在loading上使用useEffect更改执行axios。和 axios,一旦完成它的工作,就会将loading更改为false。我能想到的几种方法 -
这能回答你的问题吗? Using async setState
标签: reactjs