繁体   English   中英

Express React Socket.io编译错误

[英]Express React Socket.io Compilation Error

我正在构建一个带有React的Web单页应用程序,该应用程序使用socket.io websocket与我的快速后端连接。 我检查了是否在我的index.html文件中正确加载了socket.io脚本。 我还在同一位置声明了一个名为socket的变量,以使套接字可以从react组件脚本中访问。 目的是在我的react组件中使用此变量。 但是jsx编译器说:

9:2  error  'socket' is not defined  no-undef

如果我在chrome控制台上检查“ socket”变量,那么一切看起来都正确。 我猜这个var应该在编译时定义,但是怎么办呢?

这里是反应组件代码。

 import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; class App extends Component { componentDidMount(){ socket.on('hello', function(){ console.log('YAY!'); }) } render() { return ( <div className="App"> <div className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <h2>Welcome to React</h2> </div> </div> ); } } export default App; 

这是我的index.html代码。

 <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="shortcut icon" href="favicon.ico"> <title>React App</title> <script src="/socket.io/socket.io.js"></script> <script type="text/javascript"> var socket = io.connect('http://localhost:3001') </script> </head> <body> <div id="root"></div> </body> </html> 

首先安装socket.io,如下所示:

npm install socket.io --save

那么您应该像使用react一样将socket.io导入为模块:

import socket from 'socket.io'

解决方案在这里。

  1. 删除index.html上的所有socket.io脚本
  2. 在您的组件中导入正确的模块:

     import io from 'socket.io-client'; 
  3. 使用这种方式:

     componentWillMount(){ this.socket = io('http://localhost:3001'); this.socket.on('hello', function(){ console.log('YAY!'); }) } 

完整代码:

(index.html)

 <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="shortcut icon" href="favicon.ico"> <title>React App</title> </head> <body> <div id="root"></div> </body> </html> 

React组件(App.js)

 import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; import io from 'socket.io-client'; class App extends Component { componentWillMount(){ this.socket = io('http://localhost:3001'); this.socket.on('hello', function(){ console.log('YAY!'); }) } render() { return ( <div className="App"> <div className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <h2>Welcome to Riact</h2> </div> </div> ); } } export default App; 

暂无
暂无

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

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