[英]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'
解決方案在這里。
在您的組件中導入正確的模塊:
import io from 'socket.io-client';
使用這種方式:
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.