[英]How to expose both React development server and websocket server with ngrok
[英]React and Websocket messaging to server
因此,我遇到了顯示從資源服務器中提取的列表的單個組件的問題。 然后它使用 Stompjs 建立一個 websocket 並發送消息。 當我加載客戶端時,開發控制台顯示它嘗試調用 onConnected 方法兩次的日志,因為我的日志顯示從組件的單個加載發送的兩條 newUser 消息。
當我嘗試調用 submitBid() 方法時,它會拋出一個類型錯誤,說明
“TypeError:無法在 submitBid (AuctionList.js:76:1) 處讀取未定義的屬性(讀取‘發送’)”
我不確定為什么當它在第 36 行的 function 中定義並運行良好時,它會在該行上未定義,該行在失敗的方法之前運行。 我已經堅持了好幾天了,所以希望有人能告訴我我的代碼有什么問題......這是組件代碼......
import React from 'react'
import Stomp from 'stompjs';
import SockJS from 'sockjs-client';
import {useState, useEffect } from 'react';
function AuctionList({user, authCredentials, token}) {
const [auctionItems, setAuctionItems] = useState([]);
const [userData, setUserData] = useState({
email: user.email,
name: user.name,
message: ''
});
const [bid, setBid] = useState(0.00);
let stompClient;
let socket;
const connect = async () => {
socket = new SockJS('http://localhost:8080/ws')
stompClient = Stomp.over(socket)
stompClient.connect({}, onConnected, onError)
}
const onConnected = async () => {
stompClient.subscribe('/topic/bids', onMessageReceived)
stompClient.send("/app/socket.newUser",
{},
JSON.stringify({
sender: user.name,
type: 'NEW_USER',
time: Date.now()
})
)
}
const onError = async (err) => {
console.log(err);
}
const handleChange = async (e) =>{
setBid(e.target.value);
}
const submitBid = async (item) => {
let newMessage = {
type: "BID",
newBid: {
itemId: item.id,
email: user.email,
bidPrice: bid,
bidTime: new Date().getTime()
},
sender: userData.email,
time: new Date().getTime()
};
try {
stompClient.send("/socket.send", {}, JSON.stringify(newMessage));
} catch(err){
console.log(err); }
}
const onMessageReceived = async (payload)=>{
console.log("onMessageReceived")
console.log(payload)
}
const getAuctionList = async () => {
const url = "http://localhost:8080/auctionlist";
const init = {
method: "GET",
headers: {
'Content-type': 'application/json',
'Authorization': `Bearer ${token}`, // notice the Bearer before your token
},
};
fetch(url, init)
.then(response => response.json())
.then(response => {setAuctionItems(response)})
};
useEffect( () => {
getAuctionList();
connect();
}, []);
return (
<ul>
{auctionItems.map( item => {
return( <div key={item.id} className = "auctionItemComponent">
<h3>{item.name}</h3>
<span>{item.desc}</span>
<span>Current Bid: ${item.itemStartingPrice}</span>
<span>Minimum Bid: {item.itemMinBid}</span>
<span>Time left</span>
<input type="number" id="bidInput_" name="bidInput" onChange={handleChange} ></input>
<button type='submit' onClick={submitBid}>Submit bid</button>
</div>)
})}
</ul>
)
}
export default AuctionList
我也意識到我有一堆沒有任何等待的異步函數。 我嘗試將它們添加進去,但沒有任何變化。
這里的問題不stompjs
,而在於范圍。 您在 React Component 中有 stompClient ,但submitBid
的不同。 你可以用不同的方式來做。
將 stompjs 置於全局階段,如下所示: https://playcode.io/972045
您可以使用useRef
讓客戶端位於 React 組件中,並讓 React 跟蹤任何修改。
我個人認為像“連接”這樣的東西應該遠離 React 組件內部。 您應該將連接配置放在不同的文件中,並將實例導入 JSX 文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.