React获取和发布表单数据api.重新渲染过多



我正在React中创建通用的用户配置文件,使用api获取和发布数据。为了从表单中获取数据,我使用useState Hooks,但现在我出现了错误";重新渲染过多。React限制渲染次数,以防止出现无限循环">

代码:

const [data, setData] = useState([{}]);
const [name, setName] = useState('');
const [ic, setIc] = useState('');
const [dic, setDic] = useState('');
const [address, setAddress] = useState('');
const [city, setCity] = useState('');
const [postalCode, setPostalCode] = useState('');
const [web, setWeb] = useState('');
const [telephone, setTelephone] = useState('');
const [vatPayer, setVatPayer] = useState('');
useEffect(() => {
fetch(`${Url}subject/get`, {
method: "GET",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': `Bearer ${authManager.getToken()}`}
})
.then(response => response.json())
.then(json => setData(json))
.catch(err => console.log(err));
}, []);

const submit = async (e) => {
e.preventDefault();
const request = await fetch(`${Url}subject/update`, {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': `Bearer ${authManager.getToken()}`
},
body: JSON.stringify({
"name": name,
"ic": ic,
"dic": dic,
"address": address,
"city": city,
"postal_code": postalCode,
"web": web,
"telephone": telephone,
"vat_payer": vatPayer
})
});
const response = await request.json();

if(request.status === 200)
{
Swal.fire({
title: 'Updates',
text: response.message,
icon: 'success'
});
}
if (request.status === 401)
{
Swal.fire({
title: 'Error',
text: response.message,
icon: 'error'
});
}
};

表单代码太大了,所以我只发布了一篇:

<Row>
<Col xs={12} xl={8}>
<Card border="light" className="bg-white shadow-sm mb-4">
<Card.Body>
<h5 className="mb-4">Test</h5>
<Form onSubmit={submit}>
<Row>
<Col md={12} className="mb-3">
<Form.Group id="name">
<Form.Label>Name</Form.Label>
<Form.Control onChange={e => setName(e.target.value)} required type="text" placeholder="name" value={data.name} />
</Form.Group>
</Col>
</Row>
<Row>
<Col md={6} className="mb-3">
<Form.Group id="dphRadios">
<Form.Check
defaultChecked
type="radio"
defaultValue="neplatce"
label="Neplátce DPH"
name="platcedph"
id="neplatceRadio"
htmlFor="neplatceRadio"
onBlur={setVatPayer(0)}
checked={data.vat_payer == 0 ? true : false}
/>
<Form.Check
type="radio"
defaultValue="platce"
label="Plátce DPH"
name="platcedph"
id="platceRadio"
htmlFor="platceRadio"
onBlur={setVatPayer(1)}
checked={data.vat_payer == 1 ? true :false}
/>
</Form.Group>
</Col>
</Row>
立即调用onBlur处理程序。使用onBlur={() => setVatPayer(0)}而不是onBlur={setVatPayer(0)}
<Form.Group id="dphRadios">
<Form.Check
defaultChecked
type="radio"
defaultValue="neplatce"
label="Neplátce DPH"
name="platcedph"
id="neplatceRadio"
htmlFor="neplatceRadio"
onBlur={() => setVatPayer(0)}
checked={data.vat_payer == 0}
/>
<Form.Check
type="radio"
defaultValue="platce"
label="Plátce DPH"
name="platcedph"
id="platceRadio"
htmlFor="platceRadio"
onBlur={() => setVatPayer(1)}
checked={data.vat_payer == 1}
/>
</Form.Group>

最新更新