如何在ReactJS中更新对象格式状态的字段?



我正在使用ReactJs。我正在创建一个表单,我从用户插入值,并提交它。

我的状态是:

{
firstName: "Magnus",
lastName: "Effect",
age: 0,
}

现在我正在使用onChange函数,它接受输入的名称并更改值,如下面的代码所示。

import { Row, Form, Button, Col, Nav, Navbar, Container, NavDropdown, Offcanvas } from "react-bootstrap"
import { useState, useEffect, useRef } from 'react';
import "./App.css";
export default function App() {
const [credentials, setCredentials] = useState({
firstName: "",
lastName: "",
age: 0,
});
const onChange = (e, key) => {
setCredentials((prevCredentials) => ({
...prevCredentials,
[key]: e.target.value + "",
}));
//console.log(credentials);
};
const handleSubmit = () => {
console.log("FIrst Name : ", credentials.firstName);
console.log("Last Name : ", credentials.lastName);
console.log("Age : ", credentials.age);
}
const addAge = () => {
// only want to set the age to age+3

//I tried this but NOT working 
//setCredentials(credentials.age + 3);

console.log("New Age : ", credentials.age);
}

return <div style={{ padding: "15px" }}>

<h1>Form</h1>
<div className="container" >
<div className='col-7 mx-auto border border-1 rounded-5 bg-light border-dark p-5 mb-4'>
<Form className="fs-4">

<Form.Group
as={Row}
className="mb-3"
controlId="formBasicText"
>
<Form.Label column sm="4">
First Name
</Form.Label>
<Col>:</Col>
<Col sm="7">
<Form.Control
type="text"
value={credentials.firstName}
onChange={(e) => onChange(e, "firstName")}
placeholder="Enter Name here..."
/>
</Col>
</Form.Group>
<Form.Group
as={Row}
className="mb-3"
controlId="formBasicText"
>
<Form.Label column sm="4">
Last Name
</Form.Label>
<Col>:</Col>
<Col sm="7">
<Form.Control
type="text"
value={credentials.lastName}
onChange={(e) => onChange(e, "lastName")}
placeholder="Enter Last Name here..."
/>
</Col>
</Form.Group>
<Form.Group
as={Row}
className="mb-3"
controlId="formBasicText"
>
<Form.Label column sm="4">
Age
</Form.Label>
<Col>:</Col>
<Col sm="7">
<Form.Control
type="number"
value={credentials.age}
onChange={(e) => onChange(e, "age")}
placeholder="Enter Age here..."
/>
</Col>
</Form.Group>


<Row sm={6} className="justify-content-md-center my-3">
<Col>
<Button
variant="primary"
type="submit"
onClick={handleSubmit}
size="lg"
>
Submit
</Button>
</Col>
<Col sm={8}>
<Button
variant="primary"
type="submit"
onClick={() => addAge()}
size="lg"
>
Add 3 years to age.
</Button>
</Col>
</Row>
</Form>
</div>
</div>

</div>
}

我想在按下Add 3 yrs age后只更新credentials.age状态。我该怎么做呢?

I had try

setCredentials(credentials.age + 3);

但它不起作用?

在这里找到活动代码

setCredentials函数更新整个凭据对象,因此您需要复制凭据对象并只覆盖在副本上更改的属性。

setCredentials({...credentials, age: credentials.age + 3};

但是,由于您正在读取先前的状态作为形成新状态值的一部分,因此您实际上应该将函数传递给setCredentials,而不是像这样:

setCredentials(oldState => {
return {...oldState, age: oldState.age + 3}
});

这样做的原因是React批量状态更新,因此,例如,如果age为0,并且两个事件都想将age增加3,您希望最终年龄为6,但如果它们被批处理在一起,它们都将执行0 + 3,那么您的最终年龄将为3,而不是6。

将一个函数传递给setCredentials修复了这个问题。该函数接受最新状态,包括批处理中先前更新操作的结果,因此,如果在单个批处理中处理两个事件,第一个事件将看到oldState.age的值为0,第二个事件将看到oldState.age的值为3。

希望有帮助!这是React的一个非常基本的特性,如果你在这方面有问题,我建议你去上React的课程,祝你好运!

相关内容

  • 没有找到相关文章

最新更新