在编辑页面中,通过 redux 的 useSelector 方法,组件可以获得数据但它没有设置初始值。如何设置?
- 如何从商店设置初始 formData?
- 为什么在钩子组件渲染发生 4 次?
import React,{useState} from 'react'
import { useSelector } from 'react-redux'
import {updateUserInfo} from '../actions/User'
const EditUser = (props) => {
const user = useSelector(state => state.user)
const [formData, setFormData] = useState({email: user.email ,fullName: user.fullName})
console.log(user)
const handleSubmit = e =>{
e.preventDefault();
const id = props.match.params.id
const data = new FormData()
data.append('email', formData.email)
data.append('fullName', formData.fullName)
data.append('image', formData.image)
props.dispatch(updateUserInfo(id,data,props.history))
// console.log(formData)
}
const handleChange = e =>{
setFormData({...formData, [e.target.name]: e.target.value })
}
const fileHandle = (e) =>{
// console.log(e.target.files)
setFormData({...formData,image: e.target.files[0]})
}
return (
<React.Fragment>
<h2>Edit Account</h2>
{Object.keys(user).length > 0 &&
<>
<form onSubmit={handleSubmit}>
<label htmlFor="fullName">Full Name</label>
<input type="text" name="fullName" value={formData.fullName} onChange={handleChange}/>
<br />
<label htmlFor="email">Email</label>
<input type="email" name="email" value={formData.email} onChange={handleChange}/>
<br />
<label htmlFor="image">Upload Image</label>
<input type="file" name="image" onChange={fileHandle}/>
<br />
<button >Update</button>
</form>
</>
}
</React.Fragment>
)
}
export default EditUser