我建立了一个小船可视化器。我正在使用AISHub API。从API提取数据后,我可以获取json
我感兴趣的容器的文件,并将这些容器插入表中。用户必须按页面左上方的刷新按钮来手动更新页面,以查看新的更新表。
问题:如何设置状态以google-map
每分钟自动刷新一次内容,而不是由用户手动刷新?
代码下方:
GoogleMap.js
class BoatMap extends Component {
constructor(props) {
super(props);
this.state = {
buttonEnabled: true,
buttonClickedAt: null,
progress: 0,
ships: [],
type: 'All',
shipTypes: [],
activeShipTypes: [],
logoMap: {}
};
this.updateRequest = this.updateRequest.bind(this);
this.countDownInterval = null;
}
async componentDidMount() {
this.countDownInterval = setInterval(() => {
if (!this.state.buttonClickedAt) return;
const date = new Date();
const diff = Math.floor((date.getTime() - this.state.buttonClickedAt.getTime()) / 1000);
if (diff < 90) {
this.setState({
progress: diff,
buttonEnabled: false
});
} else {
this.setState({
progress: 0,
buttonClickedAt: null,
buttonEnabled: true
});
}
}, 500);
await this.updateRequest();
const shipTypeResults = await Client.getEntries({
content_type: 'competitors'
});
console.log(shipTypeResults);
const shipTypes = shipTypeResults.items.map((data) => data.fields);
const logoMap = shipTypes.reduce((acc, type) => {
return {
...acc,
[type.name]: type.images.fields.file.url
};
}, {});
console.log({ shipTypes });
this.setState({
logoMap
});
}
componentDidUpdate(prevProps, prevState) {
if (this.state.type !== prevState.type) {
}
}
componentWillUnmount() {
clearInterval(this.countdownInterval);
}
async updateRequest() {
const url = 'http://localhost:3001/hello';
console.log(url);
const fetchingData = await fetch(url);
const ships = await fetchingData.json();
console.log(ships);
this.setState({
buttonEnabled: false,
buttonClickedAt: new Date(),
progress: 0,
ships
});
setTimeout(() => {
this.setState({ buttonEnabled: true });
});
}
render() {
return (
<div className="google-map">
<GoogleMapReact
bootstrapURLKeys={{ key: 'KEY' }}
center={{
lat: this.props.activeShip ? this.props.activeShip.latitude : 42.4,
lng: this.props.activeShip ? this.props.activeShip.longitude : -71.1
}}
zoom={8}
>
</GoogleMapReact>
</div>
);
}
}
到目前为止,我所做的是:
一个好的方法是使用a,setTimeout()
但这是正确的吗?应该在哪里应用以及如何应用?
setTimeout(function () {
location.reload();
}, 60 * 1000);
还是将间隔设置为刷新率?
我对解决此问题的最佳方法有些困惑。
在您的请求功能上,我想您想在api不返回时禁用按钮,因此可以将这段代码移到请求上方:
this.setState({
buttonEnabled: false,
buttonClickedAt: new Date(),
progress: 0,
ships
});
如果错误,则可以从第二个setState中删除超时,并在第一个上作为回调进行调用,如下所示:
this.setState({
buttonEnabled: false,
buttonClickedAt: new Date(),
progress: 0,
ships
}, () => {
this.setState({ buttonEnabled: true });
});
在最后一部分而不是location.reload()设置一个间隔,以调用ur componentDidMount上的更新:
let updateInterval = setInterval(() => {
this.updateRequest();
}, 60 * 1000);
this.setState({updateInterval})
然后在componentWillUnmount上清除间隔 this.state.updateInterval
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句