2 回答
TA贡献1866条经验 获得超5个赞
您可以尝试将获取函数移到 componentDidMount 之外
例如:
handleClick = () => {
this.fetchdata();
}
async fetchdata(){
const url = 'http://www.boredapi.com/api/activity/'
const response = await fetch(url);
const data = await response.json();
this.setState({
activity: data.activity
})
}
componentDidMount() {
this.fetchdata();
}
TA贡献1783条经验 获得超4个赞
您可以创建一个类方法来获取新活动,
在应用程序首次安装后调用它,componentDidMount()
并在从子组件调用它时再次调用它Activity
。
您应该在问题中提到,
您提出的每个请求的响应正文都是不同的。
import React, { Component } from 'react';
import Activity from './Activity'
class App extends Component {
state = {
activity: ''
}
handleClick = () => {
this.getActivity()
}
componentDidMount() {
this.getActivity();
}
async getActivity() {
const url = 'https://www.boredapi.com/api/activity/'
const response = await fetch(url);
const data = await response.json();
this.setState({
activity: data.activity
})
}
render() {
console.log(this.state);
return (
<div>
<Activity act={this.state.activity} click={this.handleClick}/>
</div>
);
}
}
export default App;
这也是一个沙箱:
https://codesandbox.io/s/dreamy-noether-q98rf? fontsize=14&hidenavigation=1&theme=dark
添加回答
举报