【发布时间】:2021-01-27 13:29:20
【问题描述】:
我正在制作一个简单的 React 站点,它从 API (this API) 获取一些数据,然后将其显示在页面上。我使用的端点是skyblock/auctions 端点。这返回的是一个对象列表,我想获取其中的第一个,然后将其传递给子组件。父母可以成功获取数据,但是当我将它传递给孩子和console.log 它时,它返回null。我能想到它这样做的唯一原因是因为父组件还没有完成获取数据,但我不知道如何让它只在完成后渲染。
这里是父组件AuctionViewer的代码:
class AuctionViewer extends Component {
state = { data: null}
loadData = async () => {
let url = "https://api.hypixel.net/skyblock/auctions?key=INSERT_KET_HERE"
let response = await fetch(url);
let json = await response.json();
this.setState({data: json.auctions[0]}, function () {
console.log(this.state.data)
});
}
componentDidMount() {
this.loadData();
setInterval(this.loadData, 60 * 1000);
}
render() {
return (<Auction data={this.state.data} />);
}
}
这里是子组件Auction:
class Auction extends Component {
state = {
loading: true,
item: null,
price: null,
startPrice: null,
time: null,
};
loadData() {
let data = this.props.data;
console.log(data);
let end = new Date(data.end - Date.now());
let timeLeft = end.getHours() + ":" + end.getMinutes() + ":" + end.getSeconds();
this.setState({loading: false, item: data.item_name, price: data.highest_bid_amount, startPrice: data.starting_bid, time: timeLeft, timestamp: end});
};
componentDidMount() {
this.loadData();
}
render() {
return (
<div className="gridBox">
{this.state.loading ? (
<p>Loading...</p>
) : (
<div>
<p>Item: {this.state.item}</p>
<p>Top Bid: {this.state.price}</p>
<p>Start Bid: {this.state.startPrice}</p>
<p>Time Left: {this.state.time}</p>
</div>
)}
<button onClick={this.loadData}>Refresh</button>
</div>
);
}
}
【问题讨论】:
标签: javascript reactjs