簡體   English   中英

反應:為什么我的 id 未定義? axios.post 請求刪除數據而不是更新

[英]React : Why is my id undefined ? axios.post request deletes data instead of updating

感謝社區,我使用${this.props.match.params.id}解決了 axios.get 的動態 ID 問題,並且我可以訪問每個產品的編輯表單。

不幸的是,這個技巧對於發布請求似乎效率低下,我被卡住了。 當我提交表單時, axios.post中的handleSubmit會刪除我以前的數據,而不是使用新數據進行更新。 我可以看到 sql 請求有未定義的數據,尤其是id ,我不明白為什么..

我是 React 的新手,所以你能建議我如何修復我的帖子請求。

我為您提供了我的編輯表單,並且返回的一些節點可能是相關的。

編輯表格

import React, { Component } from 'react';
import { withRouter } from 'react-router';
import axios from 'axios';

import Navbar from 'react-bootstrap/Navbar';
import Nav from 'react-bootstrap/Nav';
import Form from 'react-bootstrap/Form';
import Col from 'react-bootstrap/Col';
import FormControl from 'react-bootstrap/FormControl';
import Button from 'react-bootstrap/Button';

class EditForm extends React.Component {

    constructor(props) {
        super(props);
        this.state = { product: [] };
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    };
    
    componentDidMount = () => {
        axios
        .get(`/products/edit-form/${this.props.match.params.id}`)
        .then(response => {
            console.log(response.data.products);
            this.setState({
                product: response.data.products
            })
        });    
    };

    handleChange(e) {
        this.setState({id: e.target.value})
        this.setState({reference: e.target.value})
        this.setState({designation: e.target.value})        
    }

     handleSubmit(e) {
        e.preventDefault();   
        const data = { 
        id: this.state.id,
        reference: this.state.reference,
        designation: this.state.designation        
        }  

        axios
        .post(`/products/${data.id}`, data )
        .then(res => console.log(res))      
        .catch(err => console.log(err));
    };
 
    renderForm() {
        return this.state.product.map((product, index) => {
            const { id,reference,designation } = product
        return(
            <>         
            <Form className="post" onSubmit={this.handleSubmit}>
                <Form.Row>
                    <Form.Group as={Col} controlId="formGridReference">
                    <Form.Label>Reference</Form.Label>
                    <Form.Control type="text" value={reference} 
                        onChange={this.handleChange} name="reference"  />
                    </Form.Group>

                    <Form.Group as={Col} controlId="formGridDesignation">
                    <Form.Label>Designation</Form.Label>
                    <Form.Control type="text" value={designation} 
                        onChange={this.handleChange} name="designation"  />
                    </Form.Group>
                </Form.Row>                

                <Button variant="primary" type="submit">
                    Submit
                </Button>
            </Form>
            </>
            );
        })
    }
    
    render() {
        return (
            <div>
                <h1>Formulaire de modification</h1>
                {this.renderForm()}
            </div>        
        );
    }
}

export default withRouter(EditForm);

產品

import React, { Component } from 'react';
import Table from 'react-bootstrap/Table';
import Button from 'react-bootstrap/Button';
import { Link } from 'react-router-dom';
import axios from 'axios';

const headings = [
    'id','reference','designation'
];

export default class Products extends Component {

    constructor(props) {
        super(props);
        this.state = {
            products: []
        };
    };

    componentDidMount = () => {
        axios.get("/products").then(response => {
            console.log(response.data.products);
            this.setState({
                products: response.data.products
            })
        });
    };
 
    renderTableHeader() {       
        return headings.map((key, index) => {
        return <th key={index}>{key.toUpperCase()}</th>
        })
    } 

    renderProductData() {
        return this.state.products.map((product, index) => {
            const { id,reference,designation } = product
            return (
                <tr key={id}>
                    <td>
                        {id}
                        <Link to={`/edit-form/${id}`}>Modifier</Link>
                    </td>
                    <td>{reference}</td>
                    <td>{designation}</td>                               
                </tr>
            )
        })
    }
 
    render() {
        return (
            <div>
                <h1 id='title'>Produits</h1>
                <Table striped bordered hover id='products'>
                    <thead>
                        {this.renderTableHeader()}
                    </thead>
                    <tbody>
                        {this.renderProductData()}
                    </tbody>
                </Table>
            </div>
        );
    }
}

應用程序.js

class App extends Component {
    render() {
        return (
            <React.Fragment>
                <NavBar />            
                <Router>
                    <Route exact path="/" component={Products}/>
                    <Route path="/edit-form/:id" component={EditForm}/>
                </Router>
            </React.Fragment>  
        );
    }
}

節點后端

//routes.js

    // Get All
    router.get('/products', getProducts.getProducts);
    // Get sorted
    // router.get('/products/:param', getProducts.getProductsSorted);
    // Get single
    router.get('/products/edit-form/:productId', getProducts.getProduct);
    // Update
    router.post('/products/:productId', getProducts.postProduct);


// productController.js

const getProduct = async (req, res) => 
{
    const { productId } = req.params;
    const product = await productDb.getProduct(productId);
    res.status(200).send({ products: product.rows });    
};

const postProduct = async (req, res) => 
{
    const { productId } = req.params;
    const { reference,designation } = req.body;
    await productDb.updateProduct(productId, reference, designation);
    res.status(200).send(`Le produit reference ${reference} a été modifié`);  
    console.log(`Le produit reference ${reference} a été modifié`); 


// productDb.js

const getProduct = async (id) =>
{
    const connection = new DbConnection();
    return await connection.performQuery(`SELECT * FROM produits WHERE id=${id}`);
};

const updateProduct = async (id, reference, designation) =>
{
    const connection = new DbConnection();
    await connection.performQuery("UPDATE produits SET reference=?, designation=? WHERE id=?", 
    [reference, designation, id]);
};

謝謝

我會考慮檢查 state:

 axios
        .get(`/products/edit-form/${this.props.match.params.id}`)
        .then(response => {
            console.log(response.data.products);
            this.setState({
                product: response.data.products
            })
        });   

這將product設置為一系列產品

handleChange(e) {
        this.setState({id: e.target.value})
        this.setState({reference: e.target.value})
        this.setState({designation: e.target.value})        
    }

這將設置 state id, reference, designation - 但請注意它從相同的目標值讀取 - 因此,如果參考文本字段發生更改,它將根據 @Asutosh 的評論將 id 和 designation 更改為相同的值。

 handleSubmit(e) {
        e.preventDefault();     
        const data = { 
        id: this.state.product.id,
        reference: this.state.product.reference,
        designation: this.state.product.designation        
        };

        axios
        .post(`/products/${this.props.match.params.id}`, data )
        .then(res => console.log(res))      
        .catch(err => console.log(err));
    };

這從產品中讀取,但產品是一個數組。 但是,這並不能反映handleChange設置的內容,它在根中設置id, reference, designation 這將導致 id、reference、designation 未定義,因為this.state.product是一個數組。

可以在handleChange中進行可能的更改:

        const data = { 
        id: this.state.id,
        reference: this.state.reference,
        designation: this.state.designation        
        };

但這只有在用戶更改了表單中的某些內容時才有效。 我們還需要考慮用戶可能只是點擊提交的事實。

另外,我注意到另一個錯誤(可能不相關?-閱讀評論):

  renderForm() {
        return this.state.product.map((product, index) => {
            const { id,reference,designation } = product // is this used?
        return(
            <>         
            <Form className="post" onSubmit={this.handleSubmit}>
                <Form.Row>
                    <Form.Group as={Col} controlId="formGridReference">
                    <Form.Label>Reference</Form.Label>
{/* this should be reference instead of this.state.product.reference? why is it set as placeholder? */}
                    <Form.Control type="text" value={this.state.product.reference} 
                        onChange={this.handleChange} name="reference" placeholder={reference} />
                    </Form.Group>

                    <Form.Group as={Col} controlId="formGridDesignation">
                    <Form.Label>Designation</Form.Label>
{/* this should be designation instead of this.state.product.designation? Why is designation set as a placeholder instead? */}
                    <Form.Control type="text" value={this.state.product.designation} 
                        onChange={this.handleChange} name="designation" placeholder={designation} />
                    </Form.Group>
                </Form.Row>                

                <Button variant="primary" type="submit">
                    Submit
                </Button>
            </Form>
            </>
            );
        })
    }

另外,如果目標是基於產品的單個產品提交更改,我會考慮創建一個ProductsList組件,該組件保留componentDidMount ,然后創建一個具有handleChangehandleSubmitProduct組件

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM