如何使用useState更新嵌套对象的状态,使用从React表单收集的数据?

huangapple go评论67阅读模式
英文:

How to update state of a nested object using useState with data collected from a React form?

问题

我是新手使用React。我试图创建一个简单的用户注册表单。我在使用useState hook,其中初始状态是一个嵌套对象。如何更新用户对象中的地址字段。

我的AddUser组件正在更新名字和姓氏字段,但在表单中输入街道和城市时,它不更新地址字段,而是将它们添加为新值。

import React, { useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import axios from "axios";

export default function AddUser() {

    let navigate = useNavigate();

    const [user, setUser] = useState({
        firstName: "",
        lastName: "",
        address: {
            street: "",
            city: "",
        }
    });

    const onInputChange = (e) => {
        setUser({ ...user, [e.target.name]: e.target.value });
    }

    const onSubmit = async (e) => {
        e.preventDefault();
        await axios.post("http://localhost:8080/registration/registerUser", user);
        navigate("/");
    };

    const { firstName, lastName, address: { street, city } } = user;

    return (
        <div className="container">
            <div className="row">
                <div className="col-md-6 offset-md-3 border rounded p-4 mt-2 shadow">
                    <h2 className="text-center m-4">Register User</h2>
                    <form onSubmit={(e) => onSubmit(e)}>
                        <div className="mb-3">
                            <label htmlFor="firstName" className="form-label">
                                First Name
                            </label>
                            <input
                                type="text"
                                className="form-control"
                                placeholder="Enter your name"
                                name="firstName"
                                value={firstName}
                                onChange={(e) => onInputChange(e)}
                                required
                            />
                        </div>
                        <div className="mb-3">
                            <label htmlFor="lastName" className="form-label">
                                Last Name
                            </label>
                            <input
                                type="text"
                                className="form-control"
                                placeholder="Enter your lastname"
                                name="lastName"
                                value={lastName}
                                onChange={(e) => onInputChange(e)}
                                required
                            />
                        </div>
                        <div className="mb-3">
                            <label htmlFor="street" className="form-label">
                                Street
                            </label>
                            <input
                                type="text"
                                className="form-control"
                                placeholder="Enter your street"
                                name="address.street"
                                value={street}
                                onChange={(e) => onInputChange(e)}
                                required
                            />
                        </div>
                        <div className="mb-3">
                            <label htmlFor="city" className="form-label">
                                City
                            </label>
                            <input
                                type="text"
                                className="form-control"
                                placeholder="Enter your city"
                                name="address.city"
                                value={city}
                                onChange={(e) => onInputChange(e)}
                                required
                            />
                        </div>
                        <button type="submit" className="btn btn-outline-primary">
                            Submit
                        </button>
                        <Link type="submit" className="btn btn-danger mx-2" to="/">
                            Cancel
                        </Link>
                    </form>
                </div>
            </div>
        </div>
    )
}

在这个代码中,我添加了用于更新地址字段的输入框,并相应地更新了user对象的嵌套属性。

英文:

I'm new to React. I'm trying to make a simple form to register a user. I'm using useState hook in which the initial state is a nested object. How to update address fields in user object.

My AddUser component is updating name, surname fields but when typing in the form street and city it doesn't update address fields, but adds them as new values.

import React, {useState} from &quot;react&quot;;
import {Link, useNavigate} from &quot;react-router-dom&quot;;
import axios from &quot;axios&quot;;
export default function AddUser() {
let navigate = useNavigate();
const [user, setUser] = useState({
firstName:&quot;&quot;,
lastName:&quot;&quot;,
adres: {
street:&quot;&quot;,
city:&quot;&quot;,
}
});
const onInputChange=(e)=&gt;{
setUser({...user, [e.target.name]: e.target.value});
}
const onSubmit = async (e)=&gt;{
e.preventDefault();
await axios.post(&quot;http://localhost:8080/registration/registerUser&quot;, user);
navigate(&quot;/&quot;);
};
const {firstName, lastName, street, city} = user
return (
&lt;div className=&quot;container&quot;&gt;
&lt;div className=&quot;row&quot;&gt;
&lt;div className=&quot;col-md-6 offset-md-3 border rounded p-4 mt-2 shadow&quot;&gt;
&lt;h2 className=&quot;text-center m-4&quot;&gt;Register User&lt;/h2&gt;
&lt;form onSubmit={(e)=&gt;onSubmit(e)}&gt;
&lt;div className=&quot;mb-3&quot;&gt;
&lt;label htmlFor=&quot;Firstname&quot; className=&quot;form-label&quot;&gt;
First Name
&lt;/label&gt;
&lt;input
type={&quot;text&quot;}
className=&quot;form-control&quot;
placeholder=&quot;Enter your name&quot;
name=&quot;firstName&quot;
value={firstName}
onChange={(e)=&gt;onInputChange(e)}
required
/&gt;
&lt;div className=&quot;mb-3&quot;&gt;
&lt;label htmlFor=&quot;Lastname&quot; className=&quot;form-label&quot;&gt;
Last Name
&lt;/label&gt;
&lt;input
type={&quot;text&quot;}
className=&quot;form-control&quot;
placeholder=&quot;Enter your lastname&quot;
name=&quot;lastName&quot;
value={lastName}
onChange={(e)=&gt;onInputChange(e)}
required
/&gt;
&lt;/div&gt; 
&lt;/div&gt;
&lt;button type=&quot;submit&quot; className=&quot;btn btn-outline-primary&quot;&gt;
Submit
&lt;/button&gt;
&lt;Link type=&quot;submit&quot; className=&quot;btn btn-danger mx-2&quot; to=&quot;/&quot;&gt;
Cancel
&lt;/Link&gt;
&lt;/form&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
)
}

答案1

得分: 0

const onInputChange = (e) => {
  const { name, value } = e.target;
  setUser((prevState) => ({
    ...prevState,
    adres: {
      ...prevState.adres,
      [name]: value
    }
  }));
};

这是HTML

<div className="mb-3">
  <label htmlFor="street" className="form-label">
    街道
  </label>
  <input
    type="text"
    className="form-control"
    placeholder="输入您的街道"
    name="street"
    value={user.adres.street}
    onChange={(e) => onInputChange(e)}
    required
  />
</div>
<div className="mb-3">
  <label htmlFor="city" className="form-label">
    城市
  </label>
  <input
    type="text"
    className="form-control"
    placeholder="输入您的城市"
    name="city"
    value={user.adres.city}
    onChange={(e) => onInputChange(e)}
    required
  />
</div>
英文:
const onInputChange = (e) =&gt; {
const { name, value } = e.target;
setUser((prevState) =&gt; ({
...prevState,
adres: {
...prevState.adres,
[name]: value
}
}));
};

here is html

&lt;div className=&quot;mb-3&quot;&gt;
&lt;label htmlFor=&quot;street&quot; className=&quot;form-label&quot;&gt;
Street
&lt;/label&gt;
&lt;input
type=&quot;text&quot;
className=&quot;form-control&quot;
placeholder=&quot;Enter your street&quot;
name=&quot;street&quot;
value={user.adres.street}
onChange={(e) =&gt; onInputChange(e)}
required
/&gt;
&lt;/div&gt;
&lt;div className=&quot;mb-3&quot;&gt;
&lt;label htmlFor=&quot;city&quot; className=&quot;form-label&quot;&gt;
City
&lt;/label&gt;
&lt;input
type=&quot;text&quot;
className=&quot;form-control&quot;
placeholder=&quot;Enter your city&quot;
name=&quot;city&quot;
value={user.adres.city}
onChange={(e) =&gt; onInputChange(e)}
required
/&gt;
&lt;/div&gt;

huangapple
  • 本文由 发表于 2023年2月27日 16:51:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/75578384.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定