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
添加回答
舉報