我想每1000毫秒更新一次React組件的狀態。但是,我試圖在componentDidMount
上做setInterval
,但沒有運氣。目前,我在我的console.log
中得到了兩個結果,一個是構造函數中的空狀態對象,另一個是來自API的獲取對象。如何使用setInterval每1000毫秒更新組件的狀態?在React中將setInterval添加到componentDidMount中
這是我的代碼:
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;
你能不能用'setInterval'添加你嘗試的代碼。您的代碼沒有 – atomrc
@ IsaaK08,如果您在此找到正確的解決方案,請將其設置爲已接受。 –