我是 ReactJS 的新手并使用 Hooks。我想为对象设置状态。这是我的代码:
const StartPage = (props)=> {
const [user,setUser] = useState('')
const [password,setPassword] = useState('')
const [info,setInfo] = useState({
email:''
]})
const onUserChange=(e)=>{
const user = e.target.value
setUser(user)
}
const onPasswordChange=(e)=>{
const password = e.target.value
setPassword(password)
}
const onSubmit=(e)=>{
e.preventDefault()
const myHeader = new Headers ({
'APIKey':'*****',
"Content-Type": "application/json",
'Access-Control-Allow-Origin': '*',
'Access-Control-Expose-Headers':'headers'
})
fetch(`[my_link_to_api]?username=${user}&password=${password}`,{
method:'GET',
credentials: 'omit',
headers:myHeader,
})
.then(response =>response.json())
.then(data =>{
if(data!==undefined){
setInfo({...info, data})
}
console.log(info)
})
.then(()=>{
console.log(info)
history.push({
pathname:'/dashboard',
state:info
})
})
.catch((e)=>{
console.log(e)
})
}
return (
<div>
<form onSubmit={onSubmit}>
<input type="text" placeholder="username" onChange={onUserChange}></input>
<input type="password" placeholder="password" onChange={onPasswordChange}></input>
<button>Login</button>
</form>
</div>
)
}
问题部分在这里:
我在这里声明对象初始状态:
const [info,setInfo] = useState({
email:''
})
和这里:
.then(data =>{
if(data!==undefined){
setInfo({...info, data})
}
console.log(info)
})
它只是不工作。它不是在从未写入中设置信息和数据。如何将接收到的数据(因为我控制台记录它并接收到它)分配给信息?
慕工程0101907
长风秋雁
温温酱
相关分类