Странное поведение форм
Есть react-код:
import React, { useState, useEffect } from 'react';
import { useHttp } from '../.././hooks/http.hooks';
function ChangeProfile() {
const { loading, request, error } = useHttp();
const [profile, setProfile] = useState({});
useEffect(async() => {
const email = JSON.parse(localStorage.getItem('user')).email;
const password = JSON.parse(localStorage.getItem('user')).password;
const data = await request('http://localhost:5500/api/auth/profile_to_change',
{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
user: {
email,
password
}
})
}
); // Получение данных с сервера
setProfile(data.profile);
}, []);
function changeForm(key) {
return function(ev) {
const newProfile = profile;
newProfile[key] = ev.target.value;
setProfile(newProfile);
}
}
return (
<section className="changeProfile">
<div className="container">
<table className="table">
<tr>
<td>Имя пользователя</td>
<td><input type="text" value={profile.name} onInput={changeForm('name')} /></td>
</tr>
<tr>
<td>Описание аккаунта</td>
<td><input type="text" value={profile.descr} onInput={changeForm('descr')} /></td>
</tr>
<tr>
<td>Телефон</td>
<td><input type="text" value={profile.phone} onInput={changeForm('phone')} /></td>
</tr>
<tr>
<td>Сайт</td>
<td><input type="text" value={profile.site} onInput={changeForm('site')} /></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" value={profile.email} onInput={changeForm('email')} /></td>
</tr>
<input type="button" value="Сохранить" />
</table>
</div>
</section>
);
}
export default ChangeProfile;
Почему-то при попытке изменить input он просто не меняется, а свойства в объекте profile меняются максимум на одну букву от исходных. Как можно исправить?
Ответы (1 шт):
Автор решения: Ajeet Shah
→ Ссылка
Сделай это:
const newProfile = { ...profile } // Он создает новый объект.
// или же
const newProfile = Object.assign({}, profile)
newProfile[key] = ev.target.value
setProfile(newProfile)
Не этот:
const newProfile = profile // Он использует тот же объект. // неправильный
newProfile[key] = ev.target.value
setProfile(newProfile)
Вы напрямую изменяете исходные данные. Итак, React не может обнаружить изменения.