useState 对象集 [英] useState object set
问题描述
我是 ReactJS 和 Hooks 的新手.我想为对象设置状态.这是我的代码:
const StartPage = (props)=>{const [user,setUser] = useState('')const [password,setPassword] = useState('')const [info,setInfo] = useState({电子邮件:'']})const onUserChange=(e)=>{const 用户 = e.target.value设置用户(用户)}const onPasswordChange=(e)=>{const 密码 = e.target.value设置密码(密码)}const onSubmit=(e)=>{e.preventDefault()const myHeader = 新标题 ({'APIKey':'*****',"内容类型": "应用程序/json",'Access-Control-Allow-Origin': '*','Access-Control-Expose-Headers':'headers'})fetch(`[my_link_to_api]?username=${user}&password=${password}`,{方法:'GET',凭据:'省略',标题:我的标题,}).then(response => response.json()).then(数据=>{如果(数据!==未定义){setInfo({...信息, 数据})}控制台日志(信息)}).then(()=>{控制台日志(信息)历史推送({路径名:'/仪表板',状态:信息})}).catch((e)=>{控制台日志(e)})}返回 (<div><form onSubmit={onSubmit}><input type="text" placeholder="username" onChange={onUserChange}></input><input type="password" placeholder="password" onChange={onPasswordChange}></input><button>登录</button></表单>
)}
问题部分在这里:
我在这里声明对象初始状态:
const [info,setInfo] = useState({电子邮件:''})
这里:
.then(data =>{如果(数据!==未定义){setInfo({...信息, 数据})}控制台日志(信息)})
它只是不起作用.它不是在从未写入的信息和数据中设置.如何将接收到的数据(因为我通过控制台记录并接收到)分配给信息?
setInfo
是异步的,在下一次渲染之前你不会看到更新的状态,所以当你这样做时:
if(data!==undefined){设置信息({...信息,数据})}控制台日志(信息)
您将看到 info
之前 状态更新.
你可以使用 useEffect
钩子(它告诉 React 你的组件在渲染后需要做一些事情)来查看 info
的新值:
const StartPage = props =>{const [user, setUser] = useState('');...useEffect(() => {控制台日志(信息);}, [信息]);...}
编辑
另外,正如其他人所指出的,您可能希望在设置状态时对 data
进行解构:setInfo({...info, ...data })
(这完全取决于您打算如何使用它),否则状态将如下所示:
<代码>{电子邮件: ...数据: ...}
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?
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: ...
}
这篇关于useState 对象集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!