因此,我有3个输入字段,其中一个用于输入名称,电子邮件和密码。电子邮件和密码输入字段工作正常,但是名称输入字段不允许我输入任何内容。我将输入字段的值设置为来自用户,因此它会自动填充字段。这是我的代码
import React, {useState, useEffect} from 'react';
import {useParams} from 'react-router-dom';
import {connect} from 'react-redux';
import {editUserData, fetchUserData, deleteProfile} from '../actions/index';
const EditUser = props => {
const [user, setUser] = useState({name: '', email: '', password: ''})
const params = useParams();
const editUser = e => {
e.preventDefault();
props.editUserData(params, user);
}
const handleChanges = e => {
e.persist();
setUser({...user, [e.target.name]: e.target.value});
}
useEffect(() => {
props.fetchUserData(params, setUser);
}, [])
const deleteOnClick = () => {
props.deleteProfile(params)
}
return (
<>
<form className='editUserForm' onSubmit={editUser}>
<h3>Edit Profile !</h3>
<div>Name</div>
<input className='editInput' type='text' name='name' value={`${user.firstName} ${user.lastName}`} onChange={handleChanges} />
<div>Email</div>
<input className='editInput' type='text' name='email' value={user.email} onChange={handleChanges} />
<div>Password</div>
<input className='editInput' type='text' name='password' value={user.password} onChange={handleChanges} />
<button className='submitButton'>Submit</button>
</form>
<div className='deleteProfile'>
<button className='deleteProfileButton' onClick={deleteOnClick}>Delete Profile</button>
</div>
</>
)
}
const mapStateToProps = state => {
return {
users: [],
user: {},
registerSuccessMessage: '',
user_stories: {},
isLoading: false,
error: null
}
}
export default connect(mapStateToProps, {editUserData, fetchUserData, deleteProfile})(EditUser);
编辑(根据@Boussadjra的建议)
这是props.fetchUserData之后的状态。 -setUser是- 这就是为什么我要为$ {user.firstName} $ {user.lastName}
输入值答案 0 :(得分:1)
user.firstName
和user.lastName
是未定义的,它们未定义为处于user
状态的属性,因此您应该简单地将firstName
和lastName
属性用作值:
value={ us}
或如下定义您的状态:
const [user, setUser] = useState({firstName:'',lastName:'', email: '', password: ''})
我们假设名字和姓氏之间用空格隔开,所以当您更新状态时,请使用该名字:
const handleChanges = e => {
e.persist();
if(e.target.name==='name'){
let name=e.target.value.split(' ')
setUser({...user, firstName:name[0],lastName:name[1]});
}else{
setUser({...user, [e.target.name]: e.target.value});
}
}
答案 1 :(得分:1)
这是因为要将“名称” input
的{{1}}设置为value
,即${user.firstName} ${user.lastName}
。您可以将undefined
状态设置为最初具有这些属性,但是我建议为user
,useState()
,firstName
,和lastName
(由于注释中提到,因为在单个email
中组合了姓氏和名字很容易出错):
password