[英]React state update only updates one element
Not sure what causes this issue, When I change the state using useState, the element in which its called updates but the other doesnt (shown below).不确定是什么导致了这个问题,当我使用 useState 更改状态时,它被调用的元素会更新,但另一个不会(如下所示)。 When I refresh the page, the correct one shows
当我刷新页面时,正确的显示
<>
{
user.rank != "user" && user.username != username && userInfo.rank == "user" ? <div className="profile-btn" onClick={async () => {
let res = await PromoteToMod(username)
if(res.status == 'success')
setUserInfo(state => state.rank = 'mod')
}}>
<p>PROMOTE TO MOD</p>
</div>: <></>
}
{
user.rank != "user" && user.username != username && userInfo.rank == "mod" ? <div className="profile-btn" onClick={async () => {
let res = await DemoteToUser(username)
if(res.status == 'success')
setUserInfo(state => state.rank = 'user')
}}>
<p>DEMOTE TO USER</p>
</div>: < > < />
}
</>
This is the return() from a react hook.这是来自反应钩子的 return() 。 the hook contains only one state, [userInfo, setUserInfo].
钩子只包含一种状态,[userInfo, setUserInfo]。 The userInfo is retrieved from the server thats why the correct sections shows when refreshed.
userInfo 是从服务器检索的,这就是刷新时显示正确部分的原因。 But I want to update the two buttons (PROMOTE/DEMOTE) after a response is received from the server, hence the setUserInfo call.
但是我想在从服务器收到响应后更新两个按钮(PROMOTE/DEMOTE),因此调用 setUserInfo。
Try the below approach,试试下面的方法,
{
user.rank != "user" && user.username != username && userInfo.rank == "user" ?
<div className="profile-btn" onClick={async () => {
let res = await PromoteToMod(username)
if(res.status == 'success')
setUserInfo(state => ({...state, rank:'mod'}));
}}>
<p>PROMOTE TO MOD</p>
</div>: <></>
}
similarly for rank: 'user'
rank: 'user'
类似rank: 'user'
setUserInfo(state => ({...state, rank:'user'}));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.