首页 > 解决方案 > 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;

标签: javascriptnode.jsreactjsexpresssocket.io

解决方案


推荐阅读