我想每 1000 毫秒更新一次 React 组件的状态。但是,我尝试在 componentDidMount
上执行 setInterval
,但没有成功。目前我在 console.log
中得到两个结果,一个是构造函数中的空状态对象,另一个是从 API 中获取的对象。如何使用 setInterval 每 1000 毫秒更新一次组件的状态?
这是我的代码:
let url = 'some-link-bla-bla';
class Basemap extends React.Component {
constructor(props) {
super(props);
this.state = {};
console.log(this.state);
}
render() {
return (
<Scene style={{ width: '100vw', height: '100vh' }}
mapProperties={{ basemap: 'satellite' }}
viewProperties={ this.state } />
);
}
componentDidMount() {
fetch(url)
.then(d => d.json().then(function(d) {
console.log(d);
}))
.then(d => function(d) {
this.setState({
center: [
{latitude : d.iss_position.latitude} + ', ' +
{longitude: d.iss_position.longitude}
]
})
});
}
}
export default Basemap;
最佳答案
我在 getCenter 方法中移动了对 fetch 方法的调用,我将在 componentDidMount 中将其传递给 setInterval 函数
在设置间隔之前调用 this.getCenter()。它会在安装组件后立即获取。
在 componentWillUnmount 中清除间隔。它将确保您在卸载组件后 setInterval 不会触发任何获取请求。
let url = 'some-link-bla-bla'; class Basemap extends React.Component { constructor(props) { super(props); this.state = {}; console.log(this.state); } render() { return ( <Scene style={{ width: '100vw', height: '100vh' }} mapProperties={{ basemap: 'satellite' }} viewProperties={ this.state } /> ); } componentDidMount() { // Call this function so that it fetch first time right after mounting the component this.getCenter(); // set Interval this.interval = setInterval(this.getCenter, 1000); } componentWillUnmount() { // Clear the interval right before component unmount clearInterval(this.interval); } getCenter = () => { fetch(url) .then(d => d.json().then(function(d) { console.log(d); })) .then(d => function(d) { this.setState({ center: [ {latitude : d.iss_position.latitude} + ', ' + {longitude: d.iss_position.longitude} ] }) }); } } export default Basemap;
关于javascript - 在 React 中将 setInterval 添加到 componentDidMount,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45982244/