简体   繁体   English

如何将 javascript function 放入基于 React Class 的组件中?

[英]How to put a javascript function inside a React Class based component?

I have a piece of javascript code which pings a server every second to see if it is responding properly.我有一段javascript 代码,它每秒 ping 一次服务器以查看它是否正确响应。 I want to put it inside a React Class based Component to ping a specific server address (from component state) and copy response data to the component state.我想将它放在基于 React Class 的组件中,以 ping 特定服务器地址(从组件状态)并将响应数据复制到组件 state。 I cannot work out where to put the function for it to work like I intend.不知道把 function 放在哪里,让它像我想要的那样工作。

My piece of javascript code:我的 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(); 

My React Component Structure:我的反应组件结构:

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

You could export default your myLoop function in order to be used into your function.您可以导出默认的 myLoop function 以便用于您的 function。

import ping from "../your/path/to/ping.js"

Or you could define that function inside the component, you should set an interval when your component mounts.或者您可以在组件内部定义 function,您应该在组件安装时设置间隔。

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
}

Remember to bind the ping method into your constructor.请记住将 ping 方法绑定到您的构造函数中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM