reactjs - 从 API 获取数据后如何更改状态?
问题描述
constructor(props) {
super(props);
this.state = {
message: ""
};
}
async getData() {
this.setState({...this.state})
await axios.get("https://g...")
.then(function(response) {
console.log(response);
this.setState({message: response.data})
}).bind(this)
}
render() {
return (
<div>
{this.state.message}
</div>
);
}
我尝试使用此代码从 API 获取数据。但是,打印出来的消息只链接到原来的构造函数,getData()函数并没有改变状态。获取数据后我应该如何改变状态?
解决方案
您应该使用componentDidMount,并将请求数据的函数放在 componentDidMount 生命周期中。
顺便说一句,您可以添加加载以增强用户体验:)
import React from 'react';
import "./styles.css";
const BASE_URL = 'https://api.github.com';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
message: ''
}
}
componentDidMount() {
this.getData();
}
async getData() {
try {
const result = await fetch(`${BASE_URL}/repos/facebook/react`);
const toJson = await result.json();
const stringify = JSON.stringify(toJson, null, 2);
this.setState({
message: stringify
})
} catch (error) {
// ignore error.
}
}
render() {
const { message } = this.state;
return (
<div>
{message}
</div>
)
}
}
export default App;
推荐阅读
- c - 而函数没有正确返回计数
- c# - 未重定向到 NonAuthorized 自定义错误页面
- java - 从jsp将多行插入数据库mysql
- firebase - Firebase Firestore 扩展到 Cloud Functions 以通过 Firebase 身份验证放置更多信息
- java - Java如何所有String对象都是不可变的?
- javascript - jQuery为什么在回调函数“窗口”中是$(this)?
- javascript - selenium-webdriver 在 javascript 中找不到驱动程序?
- javascript - 数组的 SetState
- xcode - 无法在 Xcode 11 中构建 GLFW 项目
- python - 使用 django 模型方法作为静态函数