问题
I am new to ReactJS and working with Hooks. I want to set state for object. Here is my code:
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>
)
}
The problem part is here:
I declare object initial state here:
const [info,setInfo] = useState({
email:''
})
And here:
.then(data =>{
if(data!==undefined){
setInfo({...info, data})
}
console.log(info)
})
it is just not working. It is not setting info and data in never written. How can I assign the received data (because I console logged it and it it received) to the info?
回答1:
setInfo is asynchronous and you won't see the updated state until the next render, so when you do this:
if(data!==undefined){
setInfo({...info, data })
}
console.log(info)
you will see info before the state was updated.
You can use useEffect hook (which tells React that your component needs to do something after render) to see the new value of info:
const StartPage = props => {
const [user, setUser] = useState('');
...
useEffect(() => {
console.log(info);
}, [info]);
...
}
EDIT
Also as others have pointed out, you likely want to destructure data when setting the state: setInfo({...info, ...data }) (this entirely depends on how you are planning to use it), otherwise the state will look like this:
{
email: ...
data: ...
}
回答2:
I'm not exactly sure what you mean by "not working" but it looks like you are deconstructing info but not data. My suspicion is that it is setting state but not the way you want. If data is an object with email as a property you most likely will want to deconstruct that too like this:
setInfo({...info, ...data})
You can use useEffect to console.log state changes if you want with something like this:
import React, { useState, useEffect } from 'react'
const StartPage = props => {
const [info,setInfo] = useState({ email:'' })
useEffect(() => {
console.log(info)
}, [info])
回答3:
What is the structure of data received from the api call? you can try setting it like so -
setInfo({ ...info, email: data.email })
来源:https://stackoverflow.com/questions/58451029/usestate-object-set