不确定是什么原因导致此问题,当我使用useState更改状态时,该元素在其中调用的元素会更新,而另一个元素不会更新(如下所示)。当我刷新页面时,显示正确的页面
<>
{
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>: < > < />
}
</>
这是React钩子的return()。挂钩仅包含一种状态[userInfo,setUserInfo]。从服务器检索到userInfo,这就是刷新后显示正确部分的原因。但是我想在从服务器收到响应后更新两个按钮(PROMOTE / DEMOTE),因此调用setUserInfo。
答案 0 :(得分:2)
尝试以下方法,
{
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>: <></>
}
类似rank: 'user'
setUserInfo(state => ({...state, rank:'user'}));