首页 > 解决方案 > 需要帮助通过正确附加 url 请求来更新 react .map 列表中的数据库数据

问题描述

短篇故事:如果我能得到帮助,弄清楚如何正确地在 URL/: id 上附加主键,我可以使用 react 和 axios 进行 .PUT crud 调用以获取 restful 功能。

更长的故事:我正在构建一个初学者的应用程序。

它有一个使用 Axios 包处理 HTTP 请求的反应前端。& 然后它有一个使用 Sequalize 连接到 Mysql 数据库的 node.js express 后端。 设置图像

目前正在尝试在 React 中发出 Axios.PUT 请求,以便能够更新 React .map 产品列表。但我还没有弄清楚如何将 /: id 附加到 URL 以成功进行更新。或让它为 crud 功能工作。

后端接收端点的工作编码如下:


        router.put("/:id", function (req, res, next) {
          let productId = parseInt(req.params.id);
          models.products
            .update(req.body, { where: { products_id: productId } })
            .then((result) => res.redirect("/products/" + productId))
            .catch((err) => {
              res.status(400);
              res.send("There was a problem updating the products.  Please check the product information.");
              console.log('There was a problem updating the product.  Please check the product information.');
           });
        });

进行 GET 和 POST 前端调用也很顺利,如下所示:

        .
import React from 'react';
import axios from 'axios';

class Products extends React.Component {
  constructor(props) {
    super(props);
    this.state = { productData: [] };
    this.productName = React.createRef();
    this.productPrice = React.createRef();
  }

  fetchProductData = () => {
    let url= http://localhost:3001/products;
    return axios.get(url).then(response => this.setState({ productData: response.data }));
      };

  componentDidMount() {
    this.fetchProductData();
  }

  addProduct = () => {
    let url = http://localhost:3001/products;
    return axios.post(url, { name: this.productName.current.value, price: this.productPrice.current.value }).then(response => {
      // refresh the data
      this.fetchProductData();
      // empty the input
      this.productName.current.value = "";
      this.productPrice.current.value = "";

    });
  };
        

我的问题和问题来自于对显示我的数据库中产品列表的 .map 列表进行 PUT & Delete 前端反应 Axios-calls。render() 显示良好,适用于 Post 和 Get 路由。

我可以使用帮助找出一种方法来正确地将:id 附加到更新产品()和删除产品()的 Axios 调用的 URL 中,这样通过输入,我可以按下按钮,然后 .map 列表更新或从列表和我的数据库中删除单个项目。我不知道如何让按钮在点击时使用正确的产品密钥。

         
  updateProduct = () => {
    let url = `http://localhost:3001/products/${product.products_id}`;
    return axios.post(url, { name: this.productName.current.value, price: this.productPrice.current.value }).then(response => {
      // refresh the data
      this.fetchProductData();
      // empty the input
      this.productName.current.value = "";
      this.productPrice.current.value = "";

    });
  };

  deleteProduct = () => {
    let url = 'http://localhost:3001/products' + ${product.products_id};
    return axios.delete((url)).then(response => {
      // refresh the data
      this.fetchProductData();
      // empty the input
      this.productName.current.value = "";
      this.productPrice.current.value = "";

    });
  };

  render() {
    console.log(this.state.productData);
    if (this.state.productData.length === 0) {
      return <div>Failed to fetch data from server</div>;
    }
    const products = this.state.productData.map(product => (
      <div key={product.products_id}>
        <em>{product.name}</em>: ${product.price} <button ref={this.updateId} type="button" className="btn btn-success" onClick={this.props.updateProduct()}>Update</button><button type="button" className="btn btn-danger" onClick={this.props.deleteProduct()}>Delete</button>
      </div>
    ));
    return (
      <div>
        <h3>List of products (React, added this code)</h3>
        <input type="text" placeholder="New Product" ref={this.productName} />
        <input type="text" placeholder="Given Price" ref={this.productPrice} />
        <button type="button" className="btn btn-primary" onClick={this.addProduct}>add</button>
        {products}
      </div>);
  }
}

export default Products;
        

列表结果的 render() 我已经研究了大约一个星期,我已经进行了大量搜索,但还没有弄清楚。抱歉,我是初学者。所以也许你们可以提供帮助。

标签: jsonreactjsdatabaseroutesaxios

解决方案


您已经在产品列表上进行了迭代,因此您可以访问产品 ID。

deleteProduct = (id) => {
    let url = `http://localhost:3001/products/${id}`;
    return axios.delete((url)).then(response => {
      // refresh the data
    });
  };

this.state.productData.map(product => (
    <button type="button" onClick={() => this.props.deleteProduct(product.id)}>Delete</button>
)

推荐阅读