如何将javascript函数放入基于React类的组件中?

如何将javascript函数放入基于React类的组件中?,javascript,node.js,reactjs,npm,Javascript,Node.js,Reactjs,Npm,我有一段javascript代码,它每秒ping一个服务器以查看它是否正确响应。我想把它放在一个基于React类的组件中ping一个特定的服务器地址(从组件状态)并将响应数据复制到组件状态。我无法确定将函数放置在何处以使其按我的意愿工作 我的一段javascript代码: var ping = require('ping'); //https://www.npmjs.com/package/ping function myLoop(c=1){ setTimeout(functio

我有一段javascript代码,它每秒ping一个服务器以查看它是否正确响应。我想把它放在一个基于React类的组件中ping一个特定的服务器地址(从组件状态)并将响应数据复制到组件状态。我无法确定将函数放置在何处以使其按我的意愿工作

我的一段javascript代码:

var ping = require('ping');    //https://www.npmjs.com/package/ping

function myLoop(c=1){
    setTimeout(function(){
        ping.promise.probe('www.google.com',{timeout:10})
            .then(function (res) {
                console.log(res);
            });
        c++;
        if(c){
            myLoop();
        }
    }, 1000);
}

myLoop(); 
我的组件结构:

class MyComponent extends React.Component{
    
    state={webAddress:'www.google.com',isAlive:false};
    
    constructor(){
        super();
    }

    componentDidMount(){
    }

    componentDidUpdate(){
    }
    
    handleSomeButtonPush(){
    }

    handleSomeTextInput(){
    }
    
    myIntendedFunction(this.state.webAddress){
        ///{.........}
        ///{.........}
        ///{.........}

        this.setState({isAlive:response.isAlive)};
    }

    render(){
        return(
            <div>
                <Component1/>
                <Component2/>
            </div>
        );
    }
}

export default MyComponent;


  [1]: https://www.npmjs.com/package/ping
类MyComponent扩展了React.Component{ state={webAddress:'www.google.com',isAlive:false}; 构造函数(){ 超级(); } componentDidMount(){ } componentDidUpdate(){ } handleSomeButtonPush(){ } 无手柄输出(){ } myIntendedFunction(this.state.webAddress){ ///{.........} ///{.........} ///{.........} this.setState({isAlive:response.isAlive)}; } render(){ 返回( ); } } 导出默认MyComponent; [1]: https://www.npmjs.com/package/ping
您可以导出myLoop函数的默认值,以便在函数中使用

import ping from "../your/path/to/ping.js"
或者您可以在组件内部定义该函数,您应该设置组件装载的间隔

componentDidMount(){
   let intervalID = setInterval(this.ping,1000);
   this.setState({ intervalID: intervalID }) // You need to add a property to your state object
}

componentWillUnmount(){
   clearInterval(this.state.intervalID);
}

ping(this.state.webAddress){
   // You define the function here using that ping library
   // If you need to clear the interval here, you could use clearInterval(this.state.intervalD) here
}
记住将ping方法绑定到构造函数中