javascript - React、Express、socket.io 没有实时更新,控制台没有错误
问题描述
我正在尝试使用 react、express 和 socket.io 制作一个实时购物清单应用程序。我设置了 socket.io 和一切,但是当我打开两个浏览器窗口并在一个窗口中添加一个项目时,另一个不会更新它的购物清单项目。虽然 console.log("made socket connection") 正在工作。
我做错了什么?
index.js
const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors");
const helmet = require("helmet");
const socket = require("socket.io");
const routes = require("./routes/api");
const app = express();
const port = process.env.port || 9000;
mongoose.connect("mongodb://localhost/shoppinglist", {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false,
});
app.use(cors());
app.use(helmet());
app.use(express.json());
app.use("/", routes);
app.use((err, req, res, next) => {
res.status(422).send({
error: err.message,
});
});
const server = app.listen(port, () => {
console.log(`now listening for requests on port ${port}`);
});
const io = socket(server);
io.on("connection", (socket) => {
console.log("made socket connection");
socket.on("item_added", (item) => {
io.sockets.emit("item_added", item);
});
});
ShoppingList.js 反应组件
import React, { Component } from "react";
import AddItem from "./AddItem";
import socketIOClient from "socket.io-client";
class ShoppingList extends Component {
state = {
id: null,
products: [],
socket: socketIOClient(
"http://localhost:9000/" + this.props.match.params.id
),
};
componentDidMount() {
this.setState({
id: this.props.match.params.id,
});
this.socketListen();
this.getItems();
}
socketListen = () => {
this.state.socket.on("item_added", (data) => {
let products = [...this.state.products, data];
this.setState({
products: products,
});
});
};
getItems = () => {
fetch("http://localhost:9000/" + this.props.match.params.id)
.then((data) => {
return data.json();
})
.then((json) => {
this.setState({
products: json,
});
});
};
addItem = (item) => {
fetch("http://localhost:9000/" + this.props.match.params.id, {
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
method: "POST",
body: JSON.stringify({
product: item.product,
quantity: item.quantity,
quantityType: item.quantityType,
}),
})
.then((response) => response.json())
.then(() => {
this.getItems();
this.state.socket.emit("item_added", {
product: item.product,
quantity: item.quantity,
quantityType: item.quantityType,
});
});
};
deleteShoppingList = () => {
fetch("http://localhost:9000/" + this.props.match.params.id, {
method: "DELETE",
})
.then((response) => response.json())
.then(() => {});
};
render() {
const itemList = this.state.products.map((product) => {
return (
<div key={product._id}>
<h2>Product: {product.product}</h2>
<h2>Quantity: {product.quantity}</h2>
<h2>Quantity type: {product.quantityType}</h2>
<button onClick={() => this.deleteItem(product)}>Delete</button>
</div>
);
});
return (
<div>
<h1 className="text-4xl font-bold text-white mb-10">Shopping list</h1>
{itemList}
<AddItem addItem={this.addItem} />
<button onClick={this.deleteShoppingList}>Delete Shopping List</button>
</div>
);
}
}
export default ShoppingList;
解决方案
推荐阅读
- reactjs - npm run-script build(production build) 命令,在 React JS 的浏览器中显示源代码
- html - 单选按钮:一次只检查一个按钮
- javascript - 我无法以使用名称的形式显示错误消息
- python - Python 3.x 中 __getattr__ 特殊方法破坏 inspect.getmembers() 的解决方法
- java - 调用某些方法时如何忽略键盘上的按键?
- windows - 使用 NSIS 写入注册表项失败
- java - 如何在休眠中创建相关子查询
- c++ - 如何使用 CFileDialog 获取包含非 ascii 字符的文件路径
- python - 类型错误:__call__() 缺少 1 个必需的位置参数:“输入”
- regex - 从perl中的字符串中提取子字符串