【发布时间】:2020-10-29 04:36:43
【问题描述】:
我正在使用钩子进行 CRUD 步骤,一切正常,但我不明白为什么在这种情况下 Axios.post 不需要 .then。
如果我只发送customer 而不是customer[0] 没有任何反应,那么.then(response => console.log(response)) 什么也不会返回。我猜customer[0] 的格式已经正确:[{}]。
import React, { useState, useEffect } from 'react';
import Axios from 'axios';
import { Form, Container, Col, Row, Button } from 'react-bootstrap';
// import data
import fields from './customerFields'; // <= array of object
function AddCustomers() {
const [customer, setCustomer] = useState([{}]);
const [inputValue, setInputValue] = useState('');
useEffect(() => {
setCustomer([inputValue]);
}, [inputValue]);
const handleSubmit = (event) => {
event.preventDefault();
const newCustomer = [...customer, inputValue];
setCustomer(newCustomer);
const url = 'http://localhost:5000/api/clients';
Axios.post(url, customer[0])
};
const handleChange = (event) => {
event.preventDefault();
const { value } = event.target;
const { name } = event.target;
const newValue = { ...inputValue, [name]: value };
setInputValue(newValue);
};
// return
return (
<Container>
<Row>
<Col className="col-form-label-sm">
<h3 id="">Identité du client</h3>
<Form
action=""
className="form-group"
onSubmit={(event) => handleSubmit(event)}
>
<Form.Group>
<Form.Label>{fields[0].label}</Form.Label>
<Form.Control
name={fields[0].name}
type="text"
value={inputValue.name}
onChange={(event) => handleChange(event)}
/>
</Form.Group>
<Form.Group>
<Form.Label>{fields[1].label}</Form.Label>
<Form.Control
name={fields[1].name}
type="text"
value={inputValue.name}
onChange={(event) => handleChange(event)}
/>
</Form.Group>
<Form.Group>
<Form.Label>{fields[2].label}</Form.Label>
<Form.Control
name={fields[2].name}
type="text"
value={inputValue.name}
onChange={(event) => handleChange(event)}
/>
</Form.Group>
<Button type="submit" variant="warning">
Ajouter un client
</Button>
</Form>
</Col>
</Row>
</Container>
);
}
export default AddCustomers;
【问题讨论】:
-
如果您不打算对响应执行任何操作,则不需要
.then。不过,我认为您派错了客户。
标签: reactjs axios react-hooks fetch crud