在React中将setInterval添加到componentDidMount

bir*_*d03 1 javascript reactjs

我想每1000毫秒更新一次React组件的状态。但是,我尝试在setInterval上进行操作componentDidMount,但是没有运气。目前,我有两个结果console.log,一个是构造函数中的空状态对象,另一个是从API提取的对象。如何使用setInterval每隔1000 ms更新一次组件的状态?

这是我的代码:

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;
Run Code Online (Sandbox Code Playgroud)

San*_*ngh 5

我将调用移至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;
    
    Run Code Online (Sandbox Code Playgroud)