javascript - react : How do you write id to have dynamic axios requests

标签 javascript reactjs axios undefined

我是 React 的新手,尽管尝试了很多次,但我无法弄清楚如何在我的编辑表单中的 axios 请求中动态设置我的 ID。

我试图用静态数字设置 axios 请求只是为了测试我的编辑表单,我可以记录我的对象但是当我提交它时删除产品数据而不是更新新数据因为 id 未定义。

我想我只需要找出在我的 componentDidMount 和 handleSubmit 中写什么来捕获 id。 例如 ${this.state.product.id} 是未定义的,为什么它不起作用?

这是我的第一个问题,所以我希望我已经清楚了,如果您需要更多代码,请告诉我。

编辑表单

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.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));
    };
 
    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={this.state.product.reference} 
                        onChange={this.handleChange} name="reference" placeholder={reference} />
                    </Form.Group>

                    <Form.Group as={Col} controlId="formGridDesignation">
                    <Form.Label>Designation</Form.Label>
                    <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>
            </>
            );
        })
    }
    
    render() {
        return (
            <div>
                <h1>Formulaire de modification</h1>
                {this.renderForm()}
            </div>        
        );
    }
}

export default withRouter(EditForm);

App.js

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

        );
    }
}

产品

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>
        );
    }
}

异步函数

// 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]);
};

谢谢

最佳答案

在您的 Products.js 中,您使用链接打开 EditForm 组件。因此,为了能够访问 product id,您需要使用 中的 withRouter hoc 包装您的 EditForm 组件react-router 库。然后,此 hoc 将使 match Prop 可用于您的 EditForm 组件。

因此,您需要通过运行以下命令将 react-router 添加到您的依赖项中:

yarn add react-router **OR** npm install react-router

然后将其添加到 EditForm.js 中的导入语句

import { withRouter } from 'react-router';

然后在 componentDidMount 中,您应该能够通过执行以下操作访问 id:

this.props.match.params.id

您还需要将类定义更改为:

class EditForm extends React.Component

然后像这样导出:

export default withRouter(EditForm)

我假设在你的 routes 文件中,你必须有一个这样定义的路由:

<Route path="/edit-form/:id" component={EditForm} />

关于javascript - react : How do you write id to have dynamic axios requests,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63092930/

相关文章:

javascript - 使用 Javascript 在浏览器中发送 SSH 命令

javascript - 从 react 应用程序的下拉列表中选择选项时按字母顺序对对象数组进行排序

javascript - 如何防止最终用户看到通过浏览器控制台进行的网络调用

javascript - React Native AXIOS方法GET response.data显示为空

javascript - 自举开关不事件

javascript - 水平表单的 Bootstrap 验证

javascript - 来自 OpenLayers 的球面墨卡托纬度/经度,需要 EPSG :4326 format

javascript - fontawesome 如何与 React 一起工作?

reactjs - 使用 ApolloClient 从 useContext Hook 导入一个简单变量

javascript - API 和网站位于同一端口的请求资源上不存在 'Access-Control-Allow-Origin' header